I am looking to make a select product category open the single product in a new tab. The other product category would behave as normal opening in the same tab.
Here is the code I have that works Globally for all products...
remove_action( 'woocommerce_before_shop_loop_item','woocommerce_template_loop_product_link_open', 10 );
add_action ( 'woocommerce_before_shop_loop_item', 'ami_function_open_new_tab', 10 );
function ami_function_open_new_tab() {
echo '<a target="_blank" href="' . get_the_permalink() . '" class="woocommerce-LoopProduct-link">';
}
This code works perfectly but I want to make it product Category Specific so here is what I came up with...
remove_action ( 'woocommerce_before_shop_loop_item','woocommerce_template_loop_product_link_open', 10 );
add_action ( 'woocommerce_before_shop_loop_item', 'ami_function_open_new_tab', 10 );
function ami_function_open_new_tab() {
if ( has_term( 'stone', 'product_cat' ) ) {
echo '<a target="_blank" href="' . get_the_permalink() . '" class="woocommerce-LoopProduct-link">';
}else if( !has_term( 'stone', 'product_cat' ) ) {
remove_action ( 'woocommerce_before_shop_loop_item', 'ami_function_open_new_tab', 10 );
add_action ( 'woocommerce_before_shop_loop_item','woocommerce_template_loop_product_link_open', 10 );
}
}
Works as expected except 1 problem
PROBLEM: the first product listed on pages for products not in the specific category dont open in a new tab or in the existing tab (wont open at all). the 2nd, 3rd,so on all open as expected.
What am I missing here?
I doubt that your remove_action can't take an action, and there are 2 links in a row. That's why the first one gives a trouble. Rest ones can be rendered by modern browser. So try this code:
add_action('init',function(){ remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 ); } ,0);
function ami_function_open_new_tab() {
//....
}
Alternatively, you can do it with simple jQuery
add_action('wp_footer',function(){
if ( has_term( 'stone', 'product_cat' ) ) {
echo '<script>
//for existing content
jQuery(".woocommerce-LoopProduct-link").attr("target","_blank");
//for content part which comes from AJAX
jQuery( document ).ajaxComplete(function() {
jQuery(".woocommerce-LoopProduct-link").attr("target","_blank");
});
</script>';
}
});