很多用户都希望在自己的wordpress网站前台增加投稿功能,虽然有很多插件可以实现此功能,但是能不用插件尽量不用插件,那么我们可以新建一个页面模板来实现投稿功能。
form表单的html代码我就不写了,这里主要写后台处理逻辑,代码如下:
$last_post = $wpdb->get_var("SELECT post_date FROM $wpdb->posts WHERE post_author='{$uid}' AND post_type = 'post' ORDER BY post_date DESC LIMIT 1"); if ( time() - strtotime($last_post) < 120 ){ print_r(json_encode(array('error'=>1, 'msg'=>'两次提交文章时间间隔太短,请稍候再来'))); exit(); } $title = $wpdb->escape($_POST['post_title']); $cat = $wpdb->escape($_POST['post_cat']); $excerpt = $wpdb->escape($_POST['post_excerpt']); $tag = $wpdb->escape($_POST['post_tag']); $content = $wpdb->escape($_POST['post_content']); if ( empty($title) || mb_strlen($title) > 50 ) { print_r(json_encode(array('error'=>1, 'msg'=>'标题不能为空,且小于50个字符'))); exit(); } if ( empty($content) || mb_strlen($content) > 10000 || mb_strlen($content) < 10 ) { print_r(json_encode(array('error'=>1, 'msg'=>'文章内容不能为空,且介于10-10000字之间'))); exit(); } $posttitle = $wpdb->get_var("SELECT post_title FROM $wpdb->posts WHERE post_author='{$uid}' AND post_title = '{$title}' LIMIT 1"); if( !empty($posttitle) ){ print_r(json_encode(array('error'=>1, 'msg'=>'标题 '. $posttitle .' 已存在'))); exit(); } $in_data = array( 'post_title' => $title, 'post_author' => $uid, 'post_excerpt' => $excerpt, 'post_content' => $content, 'tags_input' => array($tag), //格式如:array("mobantu,mbt") 'post_status' => 'pending', 'post_category' => array($cat) ); $in_id = wp_insert_post( $in_data ); if (!$in_id) { print_r(json_encode(array('error'=>1, 'msg'=>'投稿失败,请稍后再试'))); exit(); } wp_mail(get_bloginfo('admin_email'), '站长,有新投稿:'.$title, $content); print_r(json_encode(array('error'=>0, 'msg'=>'投稿成功,我们将尽快审核')));
以上代码是模板兔给客户增加的投稿代码,需要用到的同学可参考下。
2 个评论