Skip to content
Advertisement

Display custom taxonomy terms on WooCommerce shop page

I am figuring out how to display a custom taxonomy on the WooCommerce shop loop.

I found this answer, which has pointed me in the right direction. I have modified the code from that answer, to the following:

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

    $taxonomy = 'keyfeatures'; // <== Here set your custom taxonomy

   if( ! is_taxonomy( $taxonomy ) ) 
       return; // exit
    
    $term_ids = wp_get_post_terms( $product->get_id(), $taxonomy, array('fields' => 'ids') );

    if ( ! empty($term_ids) ) {
        echo get_the_term_list( $product->get_id(), 'keyfeatures', '<br /><span class="posted_in">' . _n( 'Key Feature:', 'Key Features:', count( $term_ids ), 'woocommerce' ) . ' ', ', ', '</span>' );
    }
}

The part I am stuck on is this line:

echo get_the_term_list( $product->get_id(), 'keyfeatures', '<br /><span class="posted_in">' . _n( 'Feature:', 'Features:', count( $term_ids ), 'woocommerce' ) . ' ', ', ', '</span>' );

I changed was was Vendor and Vendors (the name of the taxonomy) to Feature and Features. But I’d actually like to remove this entirely.

I would like to out put the custom taxonomy terms in the following format:

Term1 | Term2 | Term3

The line above outputs them as:

Features: Term1, Term2, Term3

I’ll also need a <span></span> around the output, so I can style it with CSS.

What changes do I make to get the desired output? (Just the taxonomy terms, separated with a pipe |, and nothing else?

###Update In the comments swadhwa suggested I look at this page, which was exactly what I needed to see.

Based on the info on that page, I changed my line of (output) code to this:

echo get_the_term_list( $product->get_id(), 'keyfeatures', '<span class="mks_prod_keyfeatures">', ' | ', '</span>' );

Yet, oddly, the output from WordPress was putting the <span class="mks_prod_keyfeatures"'></span> into the an <a ...></a> from above my taxonomy output. So I also had to change the WC hook from woocommerce_after_shop_loop_item_title to woocommerce_after_shop_loop_item. That gave the desired result.

Advertisement

Answer

You want your output to be this:

Term1 | Term2 | Term3

Then this should help:

get_the_term_list( $product->get_id(), 'keyfeatures', '<span class="posted_in">', '|', '</span>' )

where the third argument is the before content, fourth is a separator, and fifth is after content.

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