Search code examples
phpwordpresswoocommercehook-woocommerce

Woocommerce Frequently Bought Together (ADD TO CART) button rename


I'm trying to rename some specific products in woocommerce single products and frequently bought together, The below code works well for the single product buttons but how do I rename frequently bought together button for same specific products?

add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_single_loop_add_to_cart_button', 20, 1 );
function custom_single_loop_add_to_cart_button( $button_text ) {
    global $product;

    // Define your specific product IDs in this array
    $specific_ids = array(22246, 22241, 22227, 22039, 22009, 22004, 21999, 21991);
    
    if (in_array($product->get_id(), $specific_ids)) {
        $button_text = __("PRE ORDER", "woocommerce");
    } else {
        // Check if the product is purchasable
        if ($product->is_purchasable()) {
            $button_text = __("Add to Cart", "woocommerce");
        }
    }

    return $button_text;
}

Wanna rename this button, not for all but for the specified products

I have tried this code but it didn't worked

add_action( 'woocommerce_after_single_product_summary', 'custom_frequently_bought_together_button', 25 );
function custom_frequently_bought_together_button() {
    global $product;

    // Define your specific product IDs in this array
    $specific_ids = array(22246, 22241, 22227, 22039, 22009, 22004, 21999, 21991);

    // Check if the product is one of the specified ones
    if (in_array($product->get_id(), $specific_ids)) {
        // Modify the "Frequently Bought Together" button text
        add_filter( 'woocommerce_fbt_add_to_cart_text', 'custom_fbt_add_to_cart_text' );
    }
}

function custom_fbt_add_to_cart_text( $button_text ) {
    // Change the button text to "PRE ORDER" for "Frequently Bought Together" products
    return __("PRE ORDER", "woocommerce");
}

Solution

  • Try the following simplified code instead:

    add_filter( 'woocommerce_product_single_add_to_cart_text', 'filter_product_single_add_to_cart_text', 20, 2 );
    function filter_product_single_add_to_cart_text( $add_to_cart_text, $product ) {
        // Define your targeted product IDs in the array below
        $targeted_ids = array(22246, 22241, 22227, 22039, 22009, 22004, 21999, 21991);
        
        if (in_array($product->get_id(), $targeted_ids)) {
            $add_to_cart_text = __("PRE ORDER", "woocommerce");
        }
        return $add_to_cart_text;
    }
    

    It should work.