PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 9, 2022

[FIXED] How to add target=“_blank” to add to cart button on Single Product page?

 May 09, 2022     php, product, woocommerce, wordpress     No comments   

Issue

I have an affiliate website
and the button add to cart is an external link
I want that it will open in a new tab
thanks a lot


Solution

You add this piece of code to your functions.php file:

// add custom button to shop page
add_filter('woocommerce_loop_add_to_cart_link', 'shop_page_open_external_in_new_window', 10, 2);

function shop_page_open_external_in_new_window($link)
{
    global $product;
    if ($product->is_type('external')) {
        $link = sprintf(
            '<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s" target="_blank">%s</a>',
            esc_url($product->add_to_cart_url()),
            esc_attr(isset($quantity) ? $quantity : 1),
            esc_attr($product->id),
            esc_attr($product->get_sku()),
            esc_attr(isset($class) ? $class : 'button product_type_external'),
            esc_html($product->add_to_cart_text())
        );
    }

    return $link;
}

// remove default button on product page
remove_action('woocommerce_external_add_to_cart', 'woocommerce_external_add_to_cart', 30);

// add custom button on product page
add_action('woocommerce_external_add_to_cart', 'product_page_open_external_in_new_window', 30);

function product_page_open_external_in_new_window()
{
    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); ?>" rel="nofollow" class="single_add_to_cart_button button alt" target="_blank">
            <?php echo esc_html($button_text); ?>
        </a>
    </p>
<?php
    do_action('woocommerce_after_add_to_cart_button');
}

Code is tested and works.



Answered By - Jason
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing