【问题标题】:WooCommerce Display Custom Taxonomy in archiveWooCommerce 在存档中显示自定义分类
【发布时间】:2016-11-02 08:20:06
【问题描述】:

试图显示我在产品下注册的自定义分类“w_label”。但是,当我尝试使用以下代码显示它时:

register_taxonomy('w_label', array('product'), 
    array(  
        'hierarchical' => true, 
        'label' => 'Product Labels',
        'singular_label' => 'Product Label', 
        'rewrite' => true,
        'supports' => array('excerpt', 'thumbnail')

    )
);

function w_label_name () {
    global $post;
    $terms = get_the_terms( $post->ID, 'w_label' );
    foreach ( $terms as $term ){
      echo '<div class="label">' . $term->name . '</div>';
    }

}
add_action( 'woocommerce_before_shop_loop_item_title', 'w_label_name', 2 );

我不断收到“警告:为 foreach() 提供的参数无效”

不知道我错过了什么。如果我将此代码用于默认的 WooCommerce 类别,它可以工作,但不适用于我在此处注册的自定义分类。

【问题讨论】:

    标签: php wordpress woocommerce custom-taxonomy hook-woocommerce


    【解决方案1】:

    先试试看$terms = get_the_terms($post-&gt;ID, 'w_label');有没有问题在你的函数中试试this,显示$terms:

    function w_label_name () {
        global $post;
        $terms = get_the_terms( $post->ID, 'w_label' );
        echo '<div class="label">' . var_dump($terms) . '</div>';
    }
    

    然后尝试get_terms( 'w_label' ); 而不是get_the_terms( $post-&gt;ID, 'w_label' ); 并回显var_dump($terms),看看你得到了什么。

    如果你得到了什么,问题来自$term-&gt;name和获取$terms的方式。然后你可以试试这个(没有任何保证,因为未经测试):

    function w_label_name () {
        global $post;
        $terms = get_terms( 'w_label' );
        if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
            foreach ( $terms as $term ) {
                echo '<div class="label">' . $term->name . '</div>';
            }
        }
    }
    add_action( 'woocommerce_before_shop_loop_item_title', 'w_label_name', 10 );
    

    【讨论】:

    • 嘿 loic,我收到 wpobject 错误。经过一些测试后,它导致我更改为 get_terms 方法,因为我为此用例创建了此自定义分类法。
    【解决方案2】:

    这是我在产品循环中正确显示标签的代码:

    function w_label_name () {
        global $post;
        $taxonomyName = "label_name";
        terms = get_terms( $taxonomyName, array( 'hide_empty' => 0) );
        echo '<div class="label"><ul>';
            foreach ( $terms as $term ) {
                ?><li><?php echo $term->name; ?></li><?php 
            }
        echo '</ul></div>';
    }
    add_action( 'woocommerce_before_shop_loop_item_title', 'w_label_name', 2 );
    

    另请参阅 what is the difference between get_terms and get_the_terms in WordPress ? 对于 get_terms 与 get_the_terms 方法

    【讨论】:

      猜你喜欢
      • 2021-10-06
      • 2019-06-15
      • 2018-11-24
      • 2021-12-13
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多