我可以从侧边栏隐藏类别(及其子类别)吗?

时间:2012-10-16 07:37:21

标签: wordpress

我将小部件类别放在主要侧边栏上,位于信息中心。在代码上,我使用:

<?php get_sidebar('left'); ?>

并创建类别的代码。现在,我想隐藏tag_ID = 6及其所有子类别的类别。

我该怎么做?

试过这个tutorial,但似乎我没有$cat_args = "orderby=name&show_count={$c}&hierarchical={$h}";行?我正在使用最新版本的WordPress,3.4.2

1 个答案:

答案 0 :(得分:1)

教程似乎过时了,所以我不会依赖它。没有必要在WordPress-source中乱砍 - 创建一个挂钩到正确过滤器的简单插件。

在您的情况下,这些过滤器为widget_categories_dropdown_args(当您在窗口小部件选项中选择“显示为下拉列表”时)和widget_categories_args(如果窗口小部件将列表显示为带链接的普通文本)。< / p>

有了这些知识,您现在可以编写实际的插件代码(我称之为Myplugin,我认为您应该重命名它) - 只需将PHP代码放入文件wp-content/plugins/myplugin.php

<?php
/**
 * @package Myplugin
 * @version 1.0
 */
/*
Plugin Name: Myplugin
Plugin URI: http://example.com
Description: 
Author: You
Version: 1.0
Author URI: http://example.com
*/

// Create a list with the ID's of all children for 
// the given category-id
function myplugin_recursive_filter($catid) {
    $result = array($catid);

    $cats = get_categories(array(
        'child_of' => $catid,
    ));

    foreach($cats as $category) {
        $result[] = $category->cat_ID;
    }

    return implode(",", $result);
}

// Actual filter function. Just set the "exclude" 
// entry to a comma separated list of category ID's 
// to hide.
function myplugin_filter_categories_args($args) {
    // 6 is the "tag_ID"
    $args['exclude'] = myplugin_recursive_filter(6);

    // or hard code the list like that:
    //$args['exclude'] = '6,10,11,12';
    // but you'd have to include the ID's of the
    // children, because "eclude" is not recursive.
    return $args;
}

// Register the filter to the relevant tags
add_filter('widget_categories_dropdown_args',
    'myplugin_filter_categories_args', 10, 1);

add_filter('widget_categories_args',
    'myplugin_filter_categories_args', 10, 1);

函数myplugin_recursive_filter是必需的,因为exclude - 条目不是递归的(除非您在窗口小部件选项中选中“显示层次结构”)。如果您的类别没有那么大的改变,您可以用一个硬编码的ID列表(与孩子们)替换函数调用,以获得更好的性能。

相关问题