Open WooCommerce External Products in New Tab

I’m trying to customize WooCommerce external product links to open in new tabs…

This is my try:

Read More

added a filter to the WordPress theme functions.php file as the following:

add_filter( 'woocommerce_product_add_to_cart_url', 'woocommerce_externalProducts_openInNewTab' );

function woocommerce_externalProducts_openInNewTab($product_url) {

    global $product;

    if ( $product->is_type('external') ) {
        $product_url = $product->get_product_url() . '"target="_blank""';
    }

    return $product_url;

}

What did I missed?

Related posts

3 comments

  1. what you’re currently doing is wrong… get_product_url is named as what it do. It will give you the url… not the html anchor that has the url, but just the url.. so you’re just adding some text to the url.. that’s what you are doing…

    One solution is given by @Ash Patel. You can change the markup by using templates… just navigate to your plugin folder and look for this file.. woocommercetemplatessingle-productadd-to-cartexternal.php. You can find instructions inside it.

    Now, sometimes, we don’t like editing templates… especially if it’s just minor edits like this…

    Below code will do it the way you want it… just paste this code in your theme’s functions.php.

    remove_action( 'woocommerce_external_add_to_cart', 'woocommerce_external_add_to_cart', 30 );
    add_action( 'woocommerce_external_add_to_cart', 'rei_external_add_to_cart', 30 );
    function rei_external_add_to_cart(){
    
        global $product;
    
        if ( ! $product->add_to_cart_url() ) {
            return;
        }
    
        $product_url = $product->add_to_cart_url();
        $button_text = $product->single_add_to_cart_text();
    
        do_action( 'woocommerce_before_add_to_cart_button' ); ?>
        <p class="cart">
            <a href="<?php echo esc_url( $product_url ); ?>" target="_blank" rel="nofollow" class="single_add_to_cart_button button alt"><?php echo esc_html( $button_text ); ?></a>
        </p>
        <?php do_action( 'woocommerce_after_add_to_cart_button' );
    }
    
  2. Here is how you add target="_blank" to the links on archive pages:

    function ns_open_in_new_tab($args, $product) 
    {
        if( $product->is_type('external') ) {
            // Inject target="_blank" into the attributes array
            $args['attributes']['target'] = '_blank';
        }    
    
        return $args;
    }
    add_filter( 'woocommerce_loop_add_to_cart_args', 'ns_open_in_new_tab', 10, 2 );
    

    Replace ns_ part with your own namespace abbreviation.

  3. Remove above funtion from function.php:

    Use plugin files from Template folder by Template Overwrite method and then

    follow below path:
    woocommercetemplatessingle-productadd-to-cartexternal.php

    open external.php where there is a tag, apply target=”_blank”.

    it will work.

Comments are closed.