Home > Software engineering >  How to change variation color based on variation stock status in woo commerce?
How to change variation color based on variation stock status in woo commerce?

Time:12-06

working on the website built with WordPress Woocommerce and I'm trying to change the attribute background color on the product page if it is on backorder.

for example, size 4 should have a different background color, because it's out of stock and available on backorder: see image here

WPC Variation Swatches for WooCommerce by WPClever is used for attributes.

I'm implementing following code in functions.php:

function is_on_backorder() {
    if ( 'onbackorder' === $this->get_stock_status() ) {
        ?>

        <script>
        ( function( $ ) {
            'use strict';
                $( '.wpcvs-term span' ).css("background-color","red");
             ;
        } ( jQuery ) );
    </script>
<?php }
}

This is how HTML looks like:

<div class="wpcvs-terms wpcvs-type-button wpcvs-style-rounded" data-attribute="pa_size">
    <span class="wpcvs-term wpcvs-enabled wpcvs-selected" aria-label="US 4" title="US 4" data-term="us-4">
        <span>US 4</span>
    </span>
    <span class="wpcvs-term wpcvs-enabled" aria-label="US 4.5" title="US 4.5" data-term="us-4-5">
        <span>US 4.5</span>
    </span>
    <span class="wpcvs-term wpcvs-enabled" aria-label="US 5" title="US 5" data-term="us-5">
        <span>US 5</span>
    </span>
    <span class="wpcvs-term wpcvs-enabled" aria-label="US 5.5" title="US 5.5" data-term="us-5-5">
        <span>US 5.5</span>
    </span>
    <span class="wpcvs-term wpcvs-enabled" aria-label="US 6" title="US 6" data-term="us-6">
        <span>US 6</span>
    </span>
    <span class="wpcvs-term wpcvs-enabled" aria-label="US 6.5" title="US 6.5" data-term="us-6-5">
        <span>US 6.5</span>
    </span>
    <span class="wpcvs-term wpcvs-enabled" aria-label="US 7" title="US 7" data-term="us-7">
        <span>US 7</span>
    </span>
    <span class="wpcvs-term wpcvs-enabled" aria-label="US 7.5" title="US 7.5" data-term="us-7-5">
        <span>US 7.5</span>
    </span>
    <span class="wpcvs-term wpcvs-enabled" aria-label="US 8" title="US 8" data-term="us-8">
        <span>US 8</span>
    </span>
</div>

what's wrong with this code? should I add an action? how?

CodePudding user response:

First, you have to override the HTML of that variation switches. in order to do that you can use woocommerce_dropdown_variation_attribute_options_html filter hook.

But you have to remove the default filter hook of the WPC Variation Swatches plugin.

Below is the function is helps you to remove the default filter defined in-class method. Thanks to enter image description here

  • Related