How to do a Woocommerce Product list shortcode with custom taxonomy

Questo articolo è stato scritto oltre 1 years, il contenuto potrebbe essere datato.

I hate blocks, I prefer shortcode and when an official block like in this case from WooCommerce doesn’t allow you to filter by taxonomy, well it is time to create a shortcode that uses the same HTML tags, CSS classes and structure so you can do it one that works without so much problems.

function woo_ctax( $atts ) {
    $atts = shortcode_atts( array(
        'taxonomy' => 'brand',
        'term' => ''
    ), $atts, 'woo-brand-list' );

    $html = '<div class="wc-block-grid wp-block-product-tag wc-block-product-tag has-6-columns has-multiple-rows">
    <ul class="wc-block-grid__products">';
    $the_query = new WP_Query(
            'post_type' => 'product',
            'tax_query' => array(
                    'taxonomy' => $atts[ 'taxonomy' ],
                    'field'    => 'slug',
                    'terms'    => array( $atts[ 'term' ] ),
            'orderby' => 'date',
            'posts_per_page' => 6

    if ( $the_query->have_posts() ) {
        while ( $the_query->have_posts() ) {
            $_product = wc_get_product( get_the_ID() );
            $html .= '<li class="wc-block-grid__product">
                <a href="' . get_the_permalink() . '" class="wc-block-grid__product-link">
                <div class="wc-block-grid__product-image">
                ' . get_the_post_thumbnail( get_the_ID(), 'woocommerce_thumbnail' ) . '
                <div class="wc-block-grid__product-title">' . get_the_title() . '</div>
                <div class="wc-block-grid__product-price price">
                ' . $_product->get_price_html() . '


    $html .= '</ul>
        return $html;

add_shortcode( 'woo-brand-list', 'woo_ctax' );

This code as you can see is very simple.
Generate a list with the same HTML and content like the original block with a custom WP_Query using a specific taxonomy for Woocommerce products and a taxonomy term as a filter.

In case you need to do some changes in the HTML, use the original Woocommerce Product Tag block and see what are the CSS classes and changes this snippet as you need.

Liked it? Take a second to support Mte90 on Patreon!
Become a patron at Patreon!

Leave a Reply

Your email address will not be published. Required fields are marked *