Я использую код, который изменяет текст и стиль кнопки «Добавить в корзину» для товара, добавленного в корзину.
/* for single product */
add_filter( 'woocommerce_product_single_add_to_cart_text', 'single_product_button_text' );
function single_product_button_text( $text ) {
if( WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( get_the_ID() ) ) ) {
$text = 'Product in Сart';
}
return $text;
}
/* for archive/category pages */
add_filter( 'woocommerce_product_add_to_cart_text', 'products_button_text', 20, 2 );
function products_button_text( $text, $product ) {
if(
$product->is_type( 'simple' )
&& $product->is_purchasable()
&& $product->is_in_stock()
&& WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $product->get_id() ) )
) {
$text = 'Product in Сart';
}
return $text;
}
add_action( 'wp_footer', 'action_wp_footer' );
function action_wp_footer() {
?>
<script>
jQuery(document).ready(function($) {
var selector = '.add_to_cart_text:contains("Product in Сart")';
// Selector contains specific text
if ( $( selector ).length > 0 ) {
$( selector ).addClass( 'product-is-added' );
} else {
$( selector ).removeClass( 'product-is-added' );
}
});
</script>
<?php
}
После добавления товара в корзину мне приходится каждый раз обновлять страницу, чтобы получить новый текст и стиль кнопок.
Далее я использовал код для изменения текста и стиля кнопки с помощью AJAX. Текст меняется, но все стили ломаются.
add_action('wp_footer','custom_jquery_add_to_cart_script');
function custom_jquery_add_to_cart_script(){
if ( is_shop() || is_product_category() || is_product_tag() ): // Only for archives pages
$new_text = __( 'Product in Сart', 'woocommerce' );
?>
<script type="text/javascript">
// Ready state
(function($){
$('a.add_to_cart_button').click( function(){
$this = $(this);
$( document.body ).on( 'added_to_cart', function(){
$($this).text('<?php echo $new_text; ?>');
console.log('EVENT: added_to_cart');
});
});
})(jQuery);
</script>
<?php
endif;
}
Как я могу исправить этот код в своем вопросе? Может есть более корректный вариант кода?
Буду рад вашей помощи!