Stuart
Stuart

Reputation: 688

Replace a Wordpress (WooCommerce) Function

I'm using the Unite Theme with Woocommerce and need to replace the wc_get_product_cat_class function. After an entire night trying to figure it out, I have found that the following is stored in /wp-content/plugins/woocommerce/includes/wc-template-functions.php

//  Display the classes for the product cat div.
    function wc_product_cat_class( $class = '', $category = null){
     // Separates classes with a single space, collates classes for post DIV
     echo 'class="' . esc_attr( join( ' ', wc_get_product_cat_class( $class, $category ) ) ) . '"';
    }
//  Get the classes for the product cat div.
    function wc_get_product_cat_class( $class = '', $category = null ){
     global $woocommerce_loop;
     $classes   = is_array( $class ) ? $class : array_map( 'trim', explode( ' ', $class ) );
     $classes[] = 'product';
     if ( 0 === ( $woocommerce_loop['loop'] - 1 ) % $woocommerce_loop['columns'] || 1 === $woocommerce_loop['columns'] ) {
      $classes[] = 'first';
     }
     if ( 0 === $woocommerce_loop['loop'] % $woocommerce_loop['columns'] ) {
      $classes[] = 'last';
     }
     $classes = apply_filters( 'product_cat_class', $classes, $class, $category );
     return array_unique( array_filter( $classes ) );
    }

I have already created a functions.php file in my child theme already. How do I remove and replace the wc_get_product_cat_class function?

As I understand it the functions.php file in the child theme loads first, but in the absence of a if(! line in the wc-template-functions.php, I am unable to simple add and amend the above to my own functions file.

Upvotes: 1

Views: 814

Answers (1)

helgatheviking
helgatheviking

Reputation: 26319

Here's an example of how to filter the product classes via product_cat_class. I don't know exactly where you want the specific classes to appear so this is just an example. Note, $woocommerce_loop['loop'] is the position/count of the item in the loop. And it isn't in this example, but you can see it in the core wc_get_product_cat_class() function.... `$woocommerce['columns'] is the number of columns aka products per row.

function so_35164526_cat_class( $classes, $class, $category= null ){
    global $woocommerce_loop;
    if ( 0 === $woocommerce_loop['loop'] % 4 ) {
        $classes[] = 'col-md-4';
    } elseif ( 0 === $woocommerce_loop['loop'] % 2 ) {
        $classes[] = 'col-xs-2 ';
    } 
    return $classes;
}
add_filter( 'product_cat_class', 'so_35164526_cat_class', 10, 3 );

Upvotes: 1

Related Questions