Ich versuche, die Farbe aller Schaltflächen "In den Warenkorb" auf der Seite "Produkte/Archiv" zu ändern, basierend auf der Kategorie, in der sich das Produkt befindet.
Ich habe bereits einen Filter auf der Produkt-/Archivseite angewendet, um nur Produkte einer bestimmten Kategorie anzuzeigen.
Basierend auf dem folgenden Code ändert sich der Text "In den Warenkorb", die Farbe jedoch nicht.
Irgendwelche Vorschläge?
// 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;
}
Dies ist ein Filter. Es sollte einen Wert zurückgeben und nicht HTML/CSS/JS enthalten. Warum haben Sie die Vorlagendatei für Ihre Farbänderung nicht überschrieben? zB: woocomerce\single-product\add-to-cart\simple.php