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.

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

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站