WordPress功能扩展,让投稿者固定在某一个分类投稿,代码搞定啦!
前言
刚刚给一个客户要求用户投稿只能投给某个分类,而且是不审核自动发布的,考虑了下,自动发布的话,把用户角色调节到作者就可以了,然后限定分类的功能用下面的代码就可以解决了。
代码部署
以下代码放在函数文件functions.php
里面倒数第二行即可。
add_action( 'show_user_profile', 'restrict_user_form' ); add_action( 'edit_user_profile', 'restrict_user_form' ); function restrict_user_form( $user ) { if ( ! current_user_can('add_users')) return false; $args = array( 'show_option_all' => '', 'show_option_none' => '未选择', 'orderby' => 'ID', 'order' => 'ASC', 'show_count' => 0, 'hide_empty' => 0, 'child_of' => 0, 'exclude' => '', 'echo' => 1, 'selected' => get_user_meta( $user->ID, '_access', true), 'hierarchical' => 0, 'name' => 'allow', 'id' => '', 'class' => 'postform', 'depth' => 0, 'tab_index' => 0, 'taxonomy' => 'category', 'hide_if_empty' => false, 'walker' => '' ); ?> <h3>限制该用户只能投稿到分类</h3> <table class="form-table"> <tr> <th><label for="access">选择分类:</label></th> <td> <?php wp_dropdown_categories($args); ?> <br /> <span class="description">用于限制投稿者的分类目录</span> </td> </tr> </table> <?php } /* save the data from admin */ add_action( 'personal_options_update', 'restrict_save_data' ); add_action( 'edit_user_profile_update', 'restrict_save_data' ); function restrict_save_data( $user_id ) { if ( ! current_user_can( 'add_users' ) ) return false; update_user_meta( $user_id, '_access', $_POST['allow'] ); } // check if the user loggin in is author and be restricted function is_restrict() { if ( get_user_meta(get_current_user_id(), '_access', true) > 0 ) return true; else return false; } /* auto register category to post that the author's being restricted */ add_action( 'save_post', 'save_restrict_post' ); function save_restrict_post( $post_id ) { if ( ! wp_is_post_revision( $post_id ) && is_restrict() ){ remove_action('save_post', 'save_restrict_post'); wp_set_post_categories( $post_id, get_user_meta( get_current_user_id() , '_access', true) ); add_action('save_post', 'save_restrict_post'); } } /* warning author */ add_action( 'edit_form_after_title', 'restrict_warning' ); function restrict_warning( $post_data = false ) { if (is_restrict()) { $c = get_user_meta( get_current_user_id() , '_access', true); $data = get_category($c); echo 'You are allowing to post to category: <strong>'. $data->name .'</strong><br /><br />'; } } /* remove category dropdown box in editor */ function restrict_remove_meta_boxes() { if (is_restrict() ) remove_meta_box('categorydiv', 'post', 'normal'); } add_action( 'admin_menu', 'restrict_remove_meta_boxes' );
使用方法
在用户里面找到用户,点击编辑,最下面就有一个选择分类的下拉菜单,选择一个,那么这个用户只能在这个分类里面投稿了。
实际效果
-- 完 --
-- 完 --
投稿功能能不能调用别的编辑器?然后能上传文件等?
签到成功!签到时间:2015-02-20 01:21:05,每日打卡,生活更精彩哦~