Home > Back-end >  How to conditionally add classname if an element has exact text in WP/WooCommerce
How to conditionally add classname if an element has exact text in WP/WooCommerce

Time:12-15

I'm working on a webshop at the moment, and want to do some conditional rendering but I am unsure how to get it to work. Right now I have a script that gives all products within the basket a classname matching the product ID.

Some of the products are variable products, and when chosen are included within the price of a main object. The item can also be bought individually, and therefore share the same product ID. What I want to do is to add the class name only to the products which are included within the price.

My thought was to do an if-statement to determine if the product has the text " Included in the price " as its product-total, and if so add the class name. This if-statement is what is causing me grief. Here is the code that adds the class name to everything within the cart (and also the checkout page):


Gives cart items a classname equal to the product ID

function so_42237701_cart_item_class( $class, $values, $values_key ) {

    if ( isset( $values[ 'product_id' ] ) ) {
        $class .= ' custom-' . $values[ 'product_id' ];
    }

    return $class;
}
add_filter( 'woocommerce_cart_item_class', 'so_42237701_cart_item_class', 10, 3 );

And for checkout:

function additional_class_to_order_item_classes ( $class, $values, $values_key ) {

    if ( isset( $values[ 'product_id' ] ) ) {
        $class .= ' custom-' . $values[ 'product_id' ];
    }

    return $class;
}
add_filter( 'woocommerce_order_item_class', 'additional_class_to_order_item_classes', 10, 3 );

How would I get around to make it conditional?

CodePudding user response:

Variation products hold parent ID which is currently returning and also have variation ID which you can get from $values so your code should look like this

function so_42237701_cart_item_class( $class, $values, $values_key ) {
    //If we have variation ID its variable product
    if (!empty($values[ 'variation_id' ])) {
        $class .= ' custom-' . $values[ 'variation_id' ];
    } else {
        $class .= ' custom-' . $values[ 'product_id' ];
    }

    return $class;
}
add_filter( 'woocommerce_cart_item_class', 'so_42237701_cart_item_class', 10, 3 );
  • Related