简体   繁体   中英

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

I use a code that changes the text of the "Add to Cart" button for a product if the item is already in the cart.

/* 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;
 
}

Tell me how you can change the style of the "Add to Cart" button for a product if the product has already been added to the cart?

I tried adding code to /loop/add-to-cart.php file as shown here Change add to cart button style when product is in cart in Woocommerce but it doesn't work for me.

Are there any other code options that would help resolve my question?

I will be glad for your help!

One way is to check via jQuery whether a certain element (your add-to-cart button) contains a certain text, if this is the case, we will add an extra class that you can style via CSS .

:contains() Selector - Select all elements that contain the specified text.

So you get:

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' );

Note: The selector (class) can be named differently depending on the theme you are using

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM