questions

WooCommerce: Change add to cart button text for multiple products with a redirection to checkout

Rate this post

In WooCommerce, I need to change some things for two products:

  • Add to cart button (different for both products)
  • Skip cart to checkout (same for two products)

I’ve found this code, that works. But just for one product id:

add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_cart_button_text' ); 
add_filter( 'woocommerce_product_add_to_cart_text', 'custom_cart_button_text' ); 

function custom_cart_button_text($text) {
    global $woocommerce;
    global $post;
    $post_id = $post->ID;
    if($post_id == 11359){
        $text = __( 'Ja ik word kompaan', 'woocommerce' );
    }
    return $text;

}

add_filter ('woocommerce_add_to_cart_redirect', 'redirect_to_checkout');
function redirect_to_checkout($url) {
    global $woocommerce;
    if ( isset( $_POST['add-to-cart'] ) ) {
        $product_id = (int)$_POST['add-to-cart'];
        if($product_id == 11359){
            $url = $woocommerce->cart->get_checkout_url();
        }
    }
    return $url;
}

How would I make the first part of the snippet (renaming the add to cart text) so that I can use it two times; every product id needs a different add to cart text. And how can I add a second product id to the second part of the snippet (so it skips the cart for both product id’s)

Thanks!

 

✔️Solution:

You can use the following for 2 different products button texts and a redirection to checkout for both (where you will define your 2 product ids):

add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_addtocart_button_text', 10, 2 ); 
add_filter( 'woocommerce_product_add_to_cart_text', 'custom_addtocart_button_text', 10, 2 ); 
function custom_addtocart_button_text( $button_text, $product ) {
    // 1st product
    if ( $product->get_id() == 11359 ) {
        $button_text = __( 'Ja ik word kompaan', 'woocommerce' );
    } 
    // 2nd product
    elseif ( $product->get_id() == 11362 ) {
        $button_text = __( 'Something else', 'woocommerce' );
    }
    return $button_text;
}

add_filter ( 'woocommerce_add_to_cart_redirect', 'custom_redirect_to_checkout' );
function custom_redirect_to_checkout( $url ) {
    if ( isset( $_POST['add-to-cart'] ) && $_POST['add-to-cart'] > 0 ) {
        $product_id = intval( $_POST['add-to-cart'] );

        if( in_array( $product_id, array( 11359, 11362 ) ) ){
            $url = wc_get_checkout_url();
        }
    }
    return $url;
}

Code goes in functions.php file of the active child theme (or active theme). It should works.

Leave a Reply

Your email address will not be published.

Back to top button