php - WooCommerce 在存档中显示自定义分类法

标签 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 );

我不断收到“警告:为 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/

相关文章:

javascript - 查找 JavaScript 错误代码列表

php - 无法在 nginx 上更改 `upload_max_filesize`

css - 更改 WooCommerce Checkout 表单输入文本 CSS 样式

php - VS code 无法在 OSX Sierra 上访问 PHP 7.1

php - 使用循环和数组计算多个表中未发布的总发生次数

css - 条件 CSS 仅在博客上显示标题

javascript - WooCommerce cookie 和 session - 获取购物车中的当前产品

php - Woocommerce REST API - 如果实时网站上的订单与其他网站上的产品不匹配,则跳过订单传输

php - Eloquent:根据关系过滤记录

html - 如何在我的 WordPress 网站的 amp 版本上隐藏图像?