dpyln64620 2010-08-28 15:25
浏览 66
已采纳

Wordpress - 困惑,试图使用add_filter来自定义wp_list_categories

I currently have a site with a hard-coded list of categories & subcategories, where each item is formatted as follows:

<li class="cat-item open-access"><a href="/categories/open-access/">Open Access</a></li>

Importantly, each <li> item is assigned a class which matches the slug of the category linked to within.

I would obviously like to use Wordpress' wp_list_categories() to output the list instead of hard-coding it, but need to keep the custom class for each <li> item.

I have been looking into filters and actions and thought I might have come up with a fix by adding this to my theme's functions.php file:

function add_class_from_slug($wp_list_categories) {
        $pattern = '/class=\"/';
        $replacement = 'class="'.$category->slug.' ';
        $newclass = preg_replace($pattern, $replacement, $wp_list_categories);
        return $newclass;
}
add_filter('wp_list_categories','add_class_from_slug');

But this doesn't work — the text returned by $category->slug drops out when the page is rendered. If I add in static text (using a line like $replacement = 'class="myclass ';, it renders fine.

Frustratingly, I can get the output I want by adding $class .= ' '.$category->slug; at the right spot wp-includes/classes.php, but want to avoid resorting to that.

Why can't I just use $category->slug in my function? Workarounds, suggestions, further reading on the subject? Should add that I have a pretty basic grip on PHP. Thanks!

  • 写回答

1条回答 默认 最新

  • douchu5131 2010-08-28 23:20
    关注

    You can extend the Walker_Category class with your own class and override the function start_el().

    If the name of the class you used is Walker_MyCategory, you could call wp_list_categories() like:

    wp_list_categories('walker=Walker_MyCategory')
    

    You could also build your own list yourself. See get_categories()


    Oh and your code didn't work because $category wasn't defined anywhere. You need to know exactly what category it is.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容