skip to Main Content

I need to add target="_blank" to links I’m retrieving using this PHP code on a WordPress+WooCommerce installation:

$products = wc_get_products([
    'status' => 'publish', 
    'limit' => -1, 
    'product_cat' => 'talleres'
]);

$locaciones = array_map(function ($product) {
    return [
        // more code goes here, I just deleted it for this question
        'popup_html' => $product->get_categories() // this is where I need the target="_blank"
    ];
}, $products);

I tried with jQuery:

  $(document).ready( function(){
    $('a').attr('target', '_blank');
  });

But it is not working, it doesn’t add the target="_blank" to the link.

I’m thinking maybe this can be added directly to the PHP code?

3

Answers


  1. Chosen as BEST ANSWER

    Since I needed to open all and every link on a new tab, I just used <base target="_blank"> for the entire page.


  2. You may use this script. you need to add class or parent div of Anchor tag otherwise it will add to all anchors.

    jQuery(document).ready( function($){
        $('a').each(function(){
           $(this).attr('target', '_blank');
       });
      });
    
    Login or Signup to reply.
  3. You can use a php regex filter like preg_replace and search by “href” and replace the match putting the target=”_blank” before the href resulting in “target=’_blank’ href”

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search