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
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 towc_get_product_class
which ends up leveraging the filter hook ofpost_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:
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