【问题标题】:WordPress: add a customized Category Manager to the *PAGE* editorWordPress:将自定义类别管理器添加到 *PAGE* 编辑器
【发布时间】:2010-03-26 16:09:26
【问题描述】:

在 WordPress 中,post 编辑器包含一个类别面板,允许您为帖子分配类别。但是,页面 编辑器没有类别面板。我确定这是设计使然,但我需要一组经过修改的类别项目才能用于页面。

我发现我可以将下面的代码行添加到我的主题的 functions.php 文件中,以便将缺少的类别选择器添加到页面编辑器...

add_action('admin_menu', 'my_post_categories_meta_box');
function my_post_categories_meta_box() {
    add_meta_box('categorydiv', __('Categories'), 'post_categories_meta_box', 'page', 'side', 'core');
}

但是,我想指定应出现在此菜单中的类别。我不希望它列出所有可用的类别,只列出我选择包含的那些。这可能吗?

如果没有,我将如何添加一个本质上做同样事情的小部件(提供一个项目列表,旁边有复选框)?

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    最好的方法是在编辑器窗口中制作自己的元框,然后过滤掉类别或手动定义要显示的类别。

    要获得一个类别数组很简单,使用 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'); ?>" />
    

    抱歉代码量太大,我尽量精简它。

    希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多