【问题标题】:Get category ID inside "wp_list_categories" Filter在“wp_list_categories”过滤器中获取类别 ID
【发布时间】:2019-07-11 18:36:11
【问题描述】:

我在我的 wordpress 侧边栏中使用 "Categories" 小部件。 我已经使用 ACF 字段来选择类别的背景颜色。 基于 ACF 字段值,我想为每个类别的锚标记添加唯一类。

为此,我实现了以下代码。

function categories_list_filter ( $variable, $args ) {
   $term_meta = get_term_meta( 5, 'category_background', true);
   $variable = str_replace('<a ', '<a class="' . $term_meta  . '-text"', $variable);
   return $variable;
}
add_filter( 'wp_list_categories','categories_list_filter' );

如何在此过滤器中获取类别 ID?

【问题讨论】:

    标签: wordpress filter categories


    【解决方案1】:

    我好像想要得到这样的ID。

    add_filter( 'wp_list_categories', 'custom_list_categories', 999, 2 );
    function custom_list_categories( $output, $args ){
        $terms = get_categories( $args );
        $result = $output;
        if( $terms ):
            ob_start(); ?>
                <?php 
                foreach( $terms as $term ):
                    $term_meta = get_term_meta( $term->term_id, 'category_background', true); ?>
                    <li class="cat-item cat-<?php echo $term->term_id; ?>">
                        <a class="<?php echo $term_meta; ?>" href="<?php echo get_term_link( $term ); ?>"><?php echo $term->name; ?></a>
                    </li>
                     <?php
                endforeach; ?>
            <?php 
            $result = ob_get_clean();
        endif;
        return $result;
    }
    

    【讨论】:

    • 它不工作,当我return 数据它取$term_meta 变量中的最后一个值并以相同的颜色显示所有类别
    • @ParthaviPatel 是的,我忘了替换值。谢谢你:)
    • 不,它仍然无法正常工作。正如我在第一条评论中所说的那样。
    • @ParthaviPatel 请查看我最新的编辑答案。这应该适合你。
    猜你喜欢
    • 2013-07-17
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多