WordPress添加投稿功能

日期: 标签:WordPress教程
如需帮忙改代码,或者WordPress二次开发、PHP网站建设等需求,可联系我购买付费服务:  点此联系我

很多网站都想开放读者的投稿功能,接受读者的投稿,不仅可以丰富博客的内容,还可以增加与读者之间的沟通,可以说是一举多得的事情,何乐不为呢?WordPress本身并不提供投稿功能,但是WordPress拥有强大的扩展能力,我们可以自己来添加这个功能。

实现用户投稿,有两种方法,一种是开放后台的注册功能,普通用户注册进去默认设置为投稿者,登陆进去即可添加文章(默认为草稿);另一种方法是在前台提供投稿表单,用户填写相应的表格即可。前一种方法实现起来比较简单,基本不需要博主配置太多东西,只是有些博主可能会觉得别扭,不愿让他人看到自己的博客后台;而后一种方法对投稿者来说方便了很多,博主也不用担心自己博客的后台隐私,只是该方法实现起来比较麻烦,需要配置的东西很多。本文也只将介绍后一种方法,希望对你有所帮助,当然也只是复制粘贴代码就可以了。

一、添加投稿表单

1、首先在当前主题的目录下新建一个php文件,命名为tougao-page.php,然后将page.php中的所有代码复制到tougao-page.php中;

2、删除tougao-page.php开头的所有注释,即 /* 与 */ ,以及它们之间的所有内容;

3、搜索:the_content,可以查找到类似代码<?php the_content(); ?>,将其替换成代码一

如果你在tougao-page.php中找不到the_content,那么你可以查找:get_template_part,可找到类似代码:<?php get_template_part( 'content', 'page' ); ?>,将content-page.php中的所有代码替换这部分代码即可。再用下面的代码替换<?php the_content(); ?>

代码一:

<?php the_content(); ?>

<!-- 关于表单样式,请自行调整-->
<form class="ludou-tougao" method="post" action="<?php echo $_SERVER["REQUEST_URI"]; $current_user = wp_get_current_user(); ?>">
	<div style="text-align: left; padding-top: 10px;">
		<label for="tougao_authorname">昵称:*</label>
		<input type="text" size="40" value="<?php if ( 0 != $current_user->ID ) echo $current_user->user_login; ?>" id="tougao_authorname" name="tougao_authorname" />
	</div>

	<div style="text-align: left; padding-top: 10px;">
		<label for="tougao_authoremail">E-Mail:*</label>
		<input type="text" size="40" value="<?php if ( 0 != $current_user->ID ) echo $current_user->user_email; ?>" id="tougao_authoremail" name="tougao_authoremail" />
	</div>
					
	<div style="text-align: left; padding-top: 10px;">
		<label for="tougao_authorblog">您的博客:</label>
		<input type="text" size="40" value="<?php if ( 0 != $current_user->ID ) echo $current_user->user_url; ?>" id="tougao_authorblog" name="tougao_authorblog" />
	</div>

	<div style="text-align: left; padding-top: 10px;">
		<label for="tougao_title">文章标题:*</label>
		<input type="text" size="40" value="" id="tougao_title" name="tougao_title" />
	</div>

	<div style="text-align: left; padding-top: 10px;">
		<label for="tougaocategorg">分类:*</label>
		<?php wp_dropdown_categories('hide_empty=0&id=tougaocategorg&show_count=1&hierarchical=1'); ?>
	</div>
					
	<div style="text-align: left; padding-top: 10px;">
		<label style="vertical-align:top" for="tougao_content">文章内容:*</label>
		<textarea rows="15" cols="55" id="tougao_content" name="tougao_content"></textarea>
	</div>
					
	<br clear="all">
	<div style="text-align: center; padding-top: 10px;">
		<input type="hidden" value="send" name="tougao_form" />
		<input type="submit" value="提交" />
		<input type="reset" value="重填" />
	</div>
</form>

二、添加表单处理代码

在tougao-page.php开头处中,将第一个 <?php 改成代码二:

<?php
/**
 * Template Name: tougao
 * 作者:露兜
 * 博客:https://www.ludou.org/
 * 
 * 更新记录
 *  2010年09月09日 :
 *  首个版本发布
 *  
 *  2011年03月17日 :
 *  修正时间戳函数,使用wp函数current_time('timestamp')替代time()
 *  
 *  2011年04月12日 :
 *  修改了wp_die函数调用,使用合适的页面title
 *  
 *  2013年01月30日 :
 *  错误提示,增加点此返回链接
 *  
 *  2013年07月24日 :
 *  去除了post type的限制;已登录用户投稿不用填写昵称、email和博客地址
 *  
 *  2015年03月08日 :
 *  使用date_i18n('U')代替current_time('timestamp')
 */
    
if( isset($_POST['tougao_form']) && $_POST['tougao_form'] == 'send') {
    global $wpdb;
    $current_url = 'http://你的投稿页面地址';   // 注意修改此处的链接地址

    $last_post = $wpdb->get_var("SELECT `post_date` FROM `$wpdb->posts` ORDER BY `post_date` DESC LIMIT 1");

    // 博客当前最新文章发布时间与要投稿的文章至少间隔120秒。
    // 可自行修改时间间隔,修改下面代码中的120即可
    // 相比Cookie来验证两次投稿的时间差,读数据库的方式更加安全
    if ( (date_i18n('U') - strtotime($last_post)) < 120 ) {
        wp_die('您投稿也太勤快了吧,先歇会儿!<a href="'.$current_url.'">点此返回</a>');
    }
        
    // 表单变量初始化
    $name = isset( $_POST['tougao_authorname'] ) ? trim(htmlspecialchars($_POST['tougao_authorname'], ENT_QUOTES)) : '';
    $email =  isset( $_POST['tougao_authoremail'] ) ? trim(htmlspecialchars($_POST['tougao_authoremail'], ENT_QUOTES)) : '';
    $blog =  isset( $_POST['tougao_authorblog'] ) ? trim(htmlspecialchars($_POST['tougao_authorblog'], ENT_QUOTES)) : '';
    $title =  isset( $_POST['tougao_title'] ) ? trim(htmlspecialchars($_POST['tougao_title'], ENT_QUOTES)) : '';
    $category =  isset( $_POST['cat'] ) ? (int)$_POST['cat'] : 0;
    $content =  isset( $_POST['tougao_content'] ) ? trim(htmlspecialchars($_POST['tougao_content'], ENT_QUOTES)) : '';
    
    // 表单项数据验证
    if ( empty($name) || mb_strlen($name) > 20 ) {
        wp_die('昵称必须填写,且长度不得超过20字。<a href="'.$current_url.'">点此返回</a>');
    }
    
    if ( empty($email) || strlen($email) > 60 || !preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $email)) {
        wp_die('Email必须填写,且长度不得超过60字,必须符合Email格式。<a href="'.$current_url.'">点此返回</a>');
    }
    
    if ( empty($title) || mb_strlen($title) > 100 ) {
        wp_die('标题必须填写,且长度不得超过100字。<a href="'.$current_url.'">点此返回</a>');
    }
    
    if ( empty($content) || mb_strlen($content) > 3000 || mb_strlen($content) < 100) {
        wp_die('内容必须填写,且长度不得超过3000字,不得少于100字。<a href="'.$current_url.'">点此返回</a>');
    }
    
    $post_content = '昵称: '.$name.'<br />Email: '.$email.'<br />blog: '.$blog.'<br />内容:<br />'.$content;
    
    $tougao = array(
        'post_title' => $title, 
        'post_content' => $post_content,
        'post_category' => array($category)
    );


    // 将文章插入数据库
    $status = wp_insert_post( $tougao );
  
    if ($status != 0) { 
        // 投稿成功给博主发送邮件
        // somebody#example.com替换博主邮箱
        // My subject替换为邮件标题,content替换为邮件内容
        wp_mail("somebody#example.com","My subject","content");

        wp_die('投稿成功!感谢投稿!<a href="'.$current_url.'">点此返回</a>', '投稿成功');
    }
    else {
        wp_die('投稿失败!<a href="'.$current_url.'">点此返回</a>');
    }
}

最后以UTF-8编码保存tougao-page.php,否则中文可能会乱码。然后进入WordPress管理后台 – 页面 – 创建页面,标题为投稿(可以自己起名),内容填上投稿说明等,右侧可以选择模板,选择 tougao 即可。此页面即前台注册页面,将该页面的链接放到网站任何位置,供用户点击注册即可。

好了,基本的投稿功能已经添加完毕,至于表单样式不好看,表单缺少你想要的项目等问题,你就自己添加css、表单项吧。最后,也欢迎给本站投稿哦,当然本站的投稿方式是开放后台的注册功能,不是以上的表单形式。

代码补充说明

1、如果你想让投稿的文章立即发布,而不需要审核再编辑,那么请将以上代码中的:

'post_content' => $post_content,

改成:

'post_content' => $post_content,
'post_status' => 'publish',

2、如果你想让用户在投稿的同时,将投稿者注册成你本站的投稿者,并将文章的作者归到这个投稿者的名下,你可以参考此条回复的内容修改相应的代码:查看回复

3、如果你的博客文章都有自定义栏目,并且想在用户投稿的同时添加自定义栏目,可以参考这条回复:查看回复

4、如果你觉得本文提供的文章编辑框太过单调,需要一个富文本编辑,你可以看看这篇文章(包含图片上传功能):WordPress投稿功能添加富文本编辑器

5、如果你使用了一些富文本编辑器,文章提交后内容中的代码都被转义了,可以参考这条回复:查看回复

6、如果你需要投稿的文章发布后通知投稿者,可以看看这篇文章(前提投稿的文章默认是草稿状态,而不是直接发布):WordPress投稿功能添加邮件提醒功能

7、如果你想给投稿页面增加验证码功能,可以 点此下载 验证码文件,解压后将captcha目录放到当前主题目录下,然后在代码一中,将35行的:

<br clear="all">

改成:

<div style="text-align: left; padding-top: 10px;">
  <label for="CAPTCHA">验证码:
    <input id="CAPTCHA" style="width:110px;*float:left;" class="input" type="text" tabindex="24" size="10" value="" name="captcha_code" /> 看不清?<a href="javascript:void(0)" onclick="document.getElementById('captcha_img').src='<?php bloginfo('template_url'); ?>/captcha/captcha.php?'+Math.random();document.getElementById('CAPTCHA').focus();return false;">点击更换</a>
  </label>
</div>
    
<div style="text-align: left; padding-top: 10px;">
  <label>
    <img id="captcha_img" src="<?php bloginfo('template_url'); ?>/captcha/captcha.php" />
  </label>
</div>
           
<br clear="all">

将代码二中的:

if( isset($_POST['tougao_form']) && $_POST['tougao_form'] == 'send') {

改成:

if (!isset($_SESSION)) {
 	session_start();
	session_regenerate_id(TRUE);
}
 
if( isset($_POST['tougao_form']) && $_POST['tougao_form'] == 'send') {
  if(empty($_POST['captcha_code'])
    || empty($_SESSION['ludou_lcr_secretword'])
    || (trim(strtolower($_POST['captcha_code'])) != $_SESSION['ludou_lcr_secretword'])
  ) {
    wp_die('验证码不正确!<a href="'.$current_url.'">点此返回</a>');
  }

大功造成!

-- 完 --

本文采用 「CC BY-NC-SA 4.0」创作共享协议,转载请标注以下信息:
原文出处:露兜即刻 https://www.ludou.org/wordpress-add-contribute-page.html
露兜
kaapass@outlook.com  QQ 825533758

业余编程爱好者。

559 条留言

点此留言
1 9 10 11 115
  1. jack

    请教一下!

    请问标题的前方怎样加多一个预设名称?

    例如:用户输入了一个标题为 john post,当提交后在前面多了一个预先加入的名称,标题显示为 tougao john post。

    这个才是正确帖子…

1 9 10 11

发表留言