简体   繁体   English

在 WooCommerce 产品存档页面上显示自定义分类术语

[英]Display custom taxonomy terms on WooCommerce product archive pages

I've create a taxonomy called "couchages" for product with value: 1 couchage, 2 couchages, 3 couchages,…我为具有价值的产品创建了一个名为“沙发”的分类法:1 个沙发、2 个沙发、3 个沙发……

I would like to print the value of this taxonomy, for each product on the archive page, like this:我想为存档页面上的每个产品打印此分类的值,如下所示:

  • Image1,product1, price1, taxonomy value of the product 1 Image1,product1,price1,产品1的分类值
  • Image2,product2, price2, taxonomy value of the product 2 Image2,product2,price2,产品2的分类值

I would like to use a function (in my function.php) to insert this value (taxonomy).我想使用 function(在我的 function.php 中)插入这个值(分类法)。

function display_taxonomy_product_archives() {
    echo "VALUE OF THE COUCHAGE TAXONOMY";
}
add_action( 'woocommerce_after_shop_loop_item_title', 'display_taxonomy_product_archives', 25 );

Some help will be appreciated.一些帮助将不胜感激。

In the code below set your custom taxonomy to display the term names on archives pages for each product.在下面的代码中,设置您的自定义分类以在每个产品的存档页面上显示术语名称。

1) Before "add to cart" / "View more" button: 1) 在“加入购物车”/“查看更多”按钮之前:

add_action( 'woocommerce_after_shop_loop_item_title', 'display_taxonomy_product_archives', 25 );
function display_taxonomy_product_archives() {
    global $product;

    // HERE below define your custom taxonomy
    $taxonomy = 'product_cat';

    $terms = wp_get_post_terms( $product->get_id(), $taxonomy, ['fields' => 'names']);

    if( ! empty($terms) ) {
        // Display the term names 
        echo '<p class="' . $taxonomy . '">' . implode(', ', $terms) . '</p>';
    }
}

2) After "add to cart" / "View more" button: 2)“加入购物车”/“查看更多”按钮后:

add_action( 'woocommerce_after_shop_loop_item', 'display_taxonomy_product_archives', 30 );
function display_taxonomy_product_archives() {
    global $product;

    // HERE below define your custom taxonomy
    $taxonomy = 'product_cat';

    $terms = wp_get_post_terms( $product->get_id(), $taxonomy, ['fields' => 'names']);

    if( ! empty($terms) ) {
        // Display the term names 
        echo '<p class="' . $taxonomy . '" style="margin:10px 0 0">' . implode(', ', $terms) . '</p>';
    }
}

Code goes in functions.php file of your active child theme (or active theme).代码进入您的活动子主题(或活动主题)的functions.php 文件。 Tested and works.测试和工作。

Documented Wordpress wp_get_post_terms() function…记录在案的 Wordpress wp_get_post_terms()函数……

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM