试图显示我在产品下注册的自定义分类法“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 类别,它会起作用,但不适用于我在此处注册的自定义分类法。
最佳答案
首先尝试查看 $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
的方式。然后你可以试试这个(没有任何保证,因为未经测试):
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 );
关于php - WooCommerce 在存档中显示自定义分类法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38119686/