Open WooCommerce External Products in New Tab

2019-08-15 03:03发布

I'm trying to customize WooCommerce external product links to open in new tabs...

This is my try:

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?

3条回答
爷、活的狠高调
2楼-- · 2019-08-15 03:33

Remove above funtion from function.php:

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

follow below path: woocommerce\templates\single-product\add-to-cart\external.php

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

it will work.

查看更多
狗以群分
3楼-- · 2019-08-15 03:51

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.. woocommerce\templates\single-product\add-to-cart\external.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' );
}
查看更多
倾城 Initia
4楼-- · 2019-08-15 03:55

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.

查看更多
登录 后发表回答