最好的方法是在编辑器窗口中制作自己的元框,然后过滤掉类别或手动定义要显示的类别。
要获得一个类别数组很简单,使用 wordpress 的get_categories 函数来获得一个类别数组,然后如果你想从选项中删除一些类别,那么只需从该数组中unset 它们。
这是我在functions.php中的简短摘录,本质上它链接到我自己的php文件,其中包含用于选择类别然后保存的代码。
首先展示如何制作自定义编辑部分。
add_action('admin_menu', 'custom_admin');
/* Adds a custom section to the "side" of the post edit screen */
function custom_admin() {
add_meta_box('category_selector', 'Settings', 'category_custom_box', 'post', 'side', 'low');
/* prints the custom field in the new custom post section */
function category_custom_box() {
//get post meta values
global $post;
//$currentCat gets the pages current category id
$currentCat = wp_get_post_categories($post->ID);
//Do your printing of the form here.
}
然后为保存类别创建一个新函数并将其添加到 'save_post' 钩子中。
/* when the post is saved, save the custom data */
function save_postdata($post_id) {
// verify this with nonce because save_post can be triggered at other times
if (!wp_verify_nonce($_POST['customCategory_noncename'], 'customCategory')) return $post_id;
// do not save if this is an auto save routine
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
//get the category and set it
$custom_category = $_POST['custom_category'];
wp_set_post_categories($post_id, array($custom_category));
...
}
nonce 值只是一个随机生成的字符串,用于检查会话是否有效,避免并发,只需将其添加到您的表单中,
<input type="hidden" name="customCategory_noncename" id="customCategory_noncename" value="<?= wp_create_nonce('customCategory'); ?>" />
抱歉代码量太大,我尽量精简它。
希望这会有所帮助:)