skip to Main Content

I want to add some Bootstrap styles to the product item in the loop.

I know, that there is an extra template for that. And inside the template file content-product.php I could add some code to the wc_product_class function. Like this:

<li <?php wc_product_class( 'col-6 col-lg-4', $product ); ?>>

But now the class is added to every loop item in the shop. Like on the single product template inside the related products.

I know I could add some if/else and check on which page I am and add the styles for every page.
But I wonder if there is a better solution. Is there any way to add the class programmatically or hook the function?

In this case I could change/add the class only if I’m in the loop for example and I don’t have to add a lot of code in the template file.

2

Answers


  1. You could definitely leverage a filter here, but for controlling it for placement, you may need to do some remove_filter after it runs in the event it starts to bleed into other parts of the page.

    So for the wc_product_class function, it makes a call to wc_get_product_class which ends up leveraging the filter hook of post_class. If you want to control the classes using this, you’ll probably want to hook on that.

    The filter (seen here) takes 3 arguments:

    $classes : The array of class names to be added

    $class : An array or string of class names that are being added, in this case ‘col-6 col-lg-4’.

    $post_id: The post ID/ Product ID being used.

    You’ll probably need to write something like the following:

    add_filter('post_class', function($classes, $class, $product_id) {
        if(is_product_category()) {
            //only add these classes if we're on a product category page.
            $classes = array_merge(['col-6','col-lg-4'], $classes);
        }
        return $classes;
    },10,3);
    
    Login or Signup to reply.
  2. In the woocommerce plugin ‘3.6.2’ the file ‘wc-template-functions.php’ it says:

    // Note, to change classes you will need to use the newer woocommerce_post_class filter.

    My full answer is here:

    Full answer

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search