Skip to content
Advertisement

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,…

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
  • Image2,product2, price2, taxonomy value of the product 2

I would like to use a function (in my function.php) to insert this value (taxonomy).

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.

Advertisement

Answer

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:

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:

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). Tested and works.

Documented WordPress wp_get_post_terms() function…

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement