Friday, March 4, 2022

[FIXED] How to add target blank in this woocommerce code

Issue

find this code in the business bloomber. I want to add target blank attribute in this code can any help me? function bbloomer_image_link_external_url( $html,

$post_thumbnail_id ) {
   global $product;
   if ( ! $product->is_type( 'external' ) ) return $html;
   $url = $product->add_to_cart_url();
   $pattern = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/";
   $html = preg_replace( $pattern, $url, $html);  
   return $html ;
}

Solution

You can use str_replace. just add the below line after preg_replace.

$html = str_replace('<a', '<a target="_blank" ', $html);

Complete code.

function bbloomer_image_link_external_url( $html, $post_thumbnail_id ) {
   global $product;
   if ( ! $product->is_type( 'external' ) ) return $html;
   $url = $product->add_to_cart_url();
   $pattern = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/";
   $html = preg_replace( $pattern, $url, $html );  
   $html = str_replace('<a', '<a target="_blank" ', $html);
   return $html;
}
add_filter( 'woocommerce_single_product_image_thumbnail_html', 'bbloomer_image_link_external_url', 100, 2 );

Tested and works.

enter image description here



Answered By - Bhautik

No comments:

Post a Comment

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