JohnMcCarthy JohnMcCarthy - 1 year ago 98
PHP Question

Woocommerce - Different product row setting for product-archive.php and taxonomy-product_cat.php

What I'm attempting to do

I'm aiming to display a different number of products per row on archive-product.php than taxonomy-product_cat.php.

what I've done so far

I'm using the archive-product.php as is, hooking in where I need and displaying the category thumbs, 5 per row using the filter below.

function jm_loop_columns() {
return 5; // 5 products per row
add_filter( 'storefront_loop_columns', 'jm_loop_columns', 999 );

I've copied taxonomy-product_cat.php into my child theme as the styling and layout is more involved on this page, here I'd like to display only 3 products per row.


I could use nth-child selectors to achieve the same effect but I'd prefer to stay away from doing this with CSS only.

What would be the best way to apply the above filter with different settings depending on page template? Returning 5 in archive-product.php and returning 3 in taxonomy-product_cat.php

One of many ideas I'm wrestling with is to write a conditional function with is_page or is_page_template to load a different filter setting for each template.

Would anyone recommend pursuing this direction?

Answer Source

What about using conditional tags? If you are on a product_cat taxonomy page then set the number of columns to 3. Otherwise, let it stay at 5.

function jm_loop_columns( $columns ) {
    if ( is_tax( 'product_cat' ) ){
        $columns = 3;
    } else {
        $columns = 5;
    return $columns;
add_filter( 'storefront_loop_columns', 'jm_loop_columns', 999 ); 

That will get you first and last classes in the appropriate places, but you will probably still need some CSS to change the widths.