Home > Net >  Woocommerce - Redirect Add-to-Cart on Shop page to Product Page?
Woocommerce - Redirect Add-to-Cart on Shop page to Product Page?

Time:01-20

I need to redirect my customers to the product page once they click on the add-to-cart button on the shop page.

The following code:

add_filter( 'woocommerce_loop_add_to_cart_link', 'replacing_add_to_cart_button', 10, 2 );
function replacing_add_to_cart_button( $button, $product  ) {
    $button_text = __("View product", "woocommerce");
    $button = '<a  href="' . $product->get_permalink() . '">' . $button_text . '</a>';

    return $button;
}

from the following question:

Replace add to cart button with a read more linked to product page on shop pages in WooCommerce 3

gets the job done. however it completely changes all button labels which is not what I want because I've already changed the "read more" label to "Out of Stock" but this code changes everything to "view product".

I don't want to rename the label. I already have a code that I can easily rename any translation in Woocommerce:

add_filter('gettext', x_translate_text , 20, 3);
function x_translate_text ( $translated_text, $text, $domain ) {

$translation = array (

//'Enter any translation from the translation file in Woocommerce' => 'Enter Your Translation', Example:
'Add to cart' => 'View Product',

);

if( isset( $translation[$text] ) ) {
return $translation[$text];
}

return $translated_text;

}

So all I need is a simple redirect from add-to-cart (on the shop page) to product page without changing the label.

CodePudding user response:

You should remove or comment the 4th the line of code like so:

add_filter( 'woocommerce_loop_add_to_cart_link', 'replacing_add_to_cart_button', 10, 2 );
function replacing_add_to_cart_button( $button, $product  ) {
     //the line below is responsible for the button text 
    //$button_text = __("View product", "woocommerce");
    $button = '<a  href="' . $product->get_permalink() . '">add to cart</a>';

    return $button;
}

That code is responsible for the button text or label

or your can change the $button_text value to esc_html( $product->add_to_cart_text() ) which get the button text from woo-commerce. So your code would be like so:

add_filter( 'woocommerce_loop_add_to_cart_link', 'replacing_add_to_cart_button', 10, 2 );
        function replacing_add_to_cart_button( $button, $product  ) {
             //the line below is responsible for the button text 
            $button_text = esc_html( $product->add_to_cart_text() );
            $button = '<a  href="' . $product->get_permalink() . '">'.$button_text.'</a>';
    
   return $button;
}
  • Related