WooCommerce在归档中显示自定义分类

时间:2016-06-30 09:54:40

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

尝试显示自定义分类法" 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 );

我一直在&#34;警告:为foreach()&#34;

提供的参数无效

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

2 个答案:

答案 0 :(得分:3)

首先尝试查看awk -F\| -v OFS=" " ' # set input field separator to "|" and output separator to " " function trim(str) { gsub(/^ *| *$/,"",str); # remove leading and trailing space from the field gsub(/ +/," ",str); # mind those multiple spaces as well return str # return cleaned field } { for(i=1;i<=NF;i++) # loop thru all pipe separated fields printf "%s%s", trim($i),(i<NF?OFS:ORS) # print field and OFS or } # output record separator in the end of record ' test.in 尝试在您的函数中是否存在问题,以显示$terms = get_the_terms($post->ID, 'w_label');

$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->ID, 'w_label' );以查看您的内容。

如果您得到了某些内容,则问题来自var_dump($terms)以及获取$term->name的方式。然后你可以尝试这个(没有任何保证,因为未经测试)

$terms

答案 1 :(得分:1)

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

compass.rb

另见 what is the difference between get_terms and get_the_terms in WordPress ? for get_terms vs get_the_terms method

相关问题