watcher_sk
watcher_sk

Reputation: 35

Display for a specific WooCommerce product attribute the terms list on a page

In Woocommerce, I am trying to create a simple page with all brands that I have from product attribute pa_brand. But I didn't find the correct way to make that.

So this page needs to show linked brands names as a list.

Upvotes: 1

Views: 2112

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253868

Here is a custom shortcode function that will output the linked term names list for "pa_brand" product attribute. It can be used in any page or post using the Wordpress content text editor or in php code:

add_shortcode( 'product_attribute_list', 'shortcode_product_attribute_list' );
function shortcode_product_attribute_list( $atts ) {
    // Shortcode Attributes
    $atts = shortcode_atts( array(
        'taxonomy'    => 'pa_brand',
        'orderby'     => 'name',
        'hide_empty'  => false, 
    ), $atts, 'product_attribute_list' );

    $terms = get_terms( array(
        'taxonomy'      => $atts['taxonomy'],
        'orderby'       => $atts['orderby'],
        'hide_empty'    => $atts['hide_empty'], 
    ) );

    $html = '<ul class="' . $atts['taxonomy'] . ' brands">';

    // Loop through the taxonomy terms
    foreach( $terms as $term ){
        $html .= '<li><a href="' . get_term_link( $term, $atts['taxonomy'] ) . '">' . $term->name . '</a></li>';
    }

    return $html . '</ul>'; // Return the output
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

USAGE example:

1) Inside a Page or post content text Editor (or a text widget):

[product_attribute_list]

2) On a php template or code:

echo do_shortcode("[product_attribute_list]");

You will only need to add some CSS rules to your active theme's styles.css file to get the desired design.

Upvotes: 1

Related Questions