当商品在 WooCommerce 中的购物车中时,购物车按钮的新样​​式

New style of cart button when item is in cart in WooCommerce

如果商品已在购物车中,我使用代码更改商品“添加到购物车”按钮的文本。

/* 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 cart';
    }
 
    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 cart';
 
    }
 
    return $text;
 
}

如果产品已经添加到购物车,请告诉我如何更改产品“添加到购物车”按钮的样式?

我尝试将代码添加到 /loop/add-to-cart.php 文件,如此处 但它对我不起作用。

是否有任何其他代码选项可以帮助解决我的问题?

很高兴能得到你的帮助!

一种方法是通过jQuery检查某个元素(您的添加到购物车按钮)是否包含某个文本,如果是这样,我们将添加一个额外的class您可以通过 CSS.

设置样式

:contains() Selector - Select 所有包含指定文本的元素。

所以你得到:

function action_wp_footer() {
    ?>
    <script>
        jQuery(document).ready(function($) {
            var selector = '.add_to_cart_text:contains("Product in cart")';
            
            // Selector contains specific text
            if ( $( selector ).length > 0 ) {
                $( selector ).addClass( 'product-is-added' );
            } else {
                $( selector ).removeClass( 'product-is-added' );            
            }
            
        });
    </script>
    <?php
}
add_action( 'wp_footer', 'action_wp_footer' );

注意:选择器 (class) 可以根据您使用的主题命名不同