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

Elementor shortcodes

Elementor is a popular page builder plugin for WordPress that allows you to create and customize web pages using a drag-and-drop interface. Elementor provides a wide range of built-in widgets and elements, and you can also create your own custom elements using shortcodes.

Top Quick View Plugins WooCommerce

There are several popular WooCommerce quick view plugins that provide a convenient way for customers to view product details without leaving the current page. Keep in mind that the popularity of plugins can change over time, so it’s a good idea to check for the latest information and reviews before making a decision.