Pawan Kumawat

Change “Add to Cart” Text if Product Already in Cart.

To change the “Add to Cart” text if a product is already in the cart, you can use both the `woocommerce_product_single_add_to_cart_text` and `woocommerce_product_add_to_cart_text` filters. Here’s an example of how you can achieve this:

1. Open the theme’s functions.php file in your WordPress theme directory.
2. Add the following code to the file:

 

// Change "Add to Cart" text if product is already in cart on single product page
function change_single_add_to_cart_text($text) {
    global $product;

    if ($product->is_type('simple') && $product->is_purchasable() && $product->is_in_cart()) {
        $text = __('Already in Cart', 'woocommerce');
    }

    return $text;
}
add_filter('woocommerce_product_single_add_to_cart_text', 'change_single_add_to_cart_text');

// Change "Add to Cart" text if product is already in cart on product archives (shop) page
function change_archive_add_to_cart_text($text) {
    global $product;

    if ($product->is_type('simple') && $product->is_purchasable() && $product->is_in_cart()) {
        $text = __('Already in Cart', 'woocommerce');
    }

    return $text;
}
add_filter('woocommerce_product_add_to_cart_text', 'change_archive_add_to_cart_text');

 

3. Save the changes and upload the modified functions.php file back to your server.

In this example, we use the `woocommerce_product_single_add_to_cart_text` filter to modify the “Add to Cart” text on the single product page, and the `woocommerce_product_add_to_cart_text` filter to modify the text on the product archives (shop) page. The `change_single_add_to_cart_text` function and `change_archive_add_to_cart_text` function are both used to check if the product is a simple product, is purchasable, and is already in the cart. If these conditions are met, the text is changed to “Already in Cart”. You can customize the text to your preference by modifying the `__(‘Already in Cart’, ‘woocommerce’)` part.

After making these changes, the “Add to Cart” text will be replaced with “Already in Cart” for products that are already in the cart, both on the single product page and the product archives (shop) page.

Please note that this solution assumes you are using WooCommerce for your e-commerce functionality.

Categories

Related Blogs

Calculate distance between 2 address using latitude and longitude

To calculate the distance between two locations using their latitude and longitude coordinates, you can use the Haversine formula. The Haversine formula is commonly used to calculate the great-circle distance between two points on the surface of a sphere (such as the Earth) given their latitude and longitude.