在新标签页中打开特定类别的产品

Open Product of Certain Category in a new tab

我想制作一个 select 产品类别,在新标签页中打开单个产品。其他产品类别将在同一选项卡中正常打开。

这是我拥有的适用于全球所有产品的代码...

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">';
}

这段代码工作得很好,但我想让它成为特定于产品类别的,所以这就是我想出的...

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 );
 }
}

除 1 个问题外按预期工作

问题:不属于特定类别的产品页面上列出的第一个产品不会在新选项卡或现有选项卡中打开(根本不会打开)。第二个,第三个,等等都按预期打开。

我在这里错过了什么?

我怀疑你的remove_action不能采取行动,而且连着2个链接。这就是为什么第一个会带来麻烦。其余的可以由现代浏览器呈现。 所以试试这个代码:

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() {
//....
}

或者,您可以使用简单的 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>';
}
});