1

I am trying to change the colour of all the "Add To Cart" buttons on the Products/Archive page, based on the category which the product is in.

I have a filter already applied on the products/archive page to only display products from a given category.

However, based on the code below, the "add to cart" text changes, but the colour does not.

Any suggestions?

    // Change add to cart button text per category
add_filter( 'woocommerce_product_add_to_cart_text', 'custom_single_add_to_cart_text', 20, 2 );
function custom_single_add_to_cart_text( $text_button, $product ) {
    global $post;
    $domain = 'woocommerce';

    // HERE set the array of categories terms slug and corresponding colors and texts
    $categories_colors = array(
        'protein'  => array( 'color' => 'red', 'text' => __('Order your Protein', $domain ) ),
        'pantry'   =>  array( 'color' => 'blue', 'text' => __('Order your Pantry', $domain ) ),
    );

    $color = '';
    $text_button = __('Order now', $domain ); // default

    foreach ($categories_colors as $key => $value ) {
        if( has_term( $key, 'product_cat', $post->ID ) ){
            $color = $value['color'];
            $text_button = $value['text'];
            break;
        }
    }
    if ( empty($color) ) return $text_button; // Exit if empty

    // Dynamic css andjquery to set the color when defined
    ?>
    <style>
        button.single_add_to_cart_button.<?php echo $color; ?>{background-color:<?php echo $color; ?> !important;}
    </style>
    <?php
    // jQuery (add color css class)
    ?>
    <script type="text/javascript">
        (function($){
             $('button.single_add_to_cart_button').addClass('<?php echo $color; ?>');
        })(jQuery);
    </script>
    <?php

    return $text_button;
}
  • Hi, this site is for questions about WordPress, not plugins. Please ask WooCommerce support for help. – Florian Apr 24 '18 at 13:41
0

This is a filter. It should return value, not render HTML/CSS/JS inside. For your color change, why didn't you override the template file. eg: woocomerce\single-product\add-to-cart\simple.php

Not the answer you're looking for? Browse other questions tagged or ask your own question.