製品をクリックすると新しいウィンドウが開きます。

if (!defined('ABSPATH')) exit;

/**
 * 在产品列表页(商店/分类/标签/产品归档)里,
 * 让“跳转到单品页”的链接统一新标签打开。
 * 自动跳过 add_to_cart / quick-view 等按钮。
 */
add_action('template_redirect', function () {
    if (is_admin()) return;
    if (!function_exists('is_shop')) return;

    $is_product_archive = (
        is_shop() ||
        (function_exists('is_product_category') && is_product_category()) ||
        (function_exists('is_product_tag') && is_product_tag()) ||
        is_post_type_archive('product')
    );
    if (!$is_product_archive) return;

    ob_start(function ($html) {
        // 不含 /product/ 直接略过,减少开销
        if (stripos($html, '/product/') === false) return $html;

        // 给 <a href=".../product/..."> 打 target="_blank",排除加入购物车/快速预览等
        $html = preg_replace_callback('~<a\b([^>]*?)href=(["\'])([^"\']+)\2([^>]*)>~i', function ($m) {
            $before = $m[1];   // href 前的属性
            $q      = $m[2];   // 引号
            $href   = $m[3];   // 链接
            $after  = $m[4];   // href 后的属性
            $tag    = $m[0];   // 原始 <a ...>

            $href_l = strtolower($href);
            // 只处理指向“单品页”的链接;跳过加入购物车/电话/邮件等
            if (strpos($href_l, '/product/') === false) return $tag;
            if (strpos($href_l, 'add-to-cart') !== false) return $tag;
            if (strpos($href_l, 'mailto:') !== false || strpos($href_l, 'tel:') !== false) return $tag;

            // 链接本身是“加入购物车/快速预览”等按钮类,也跳过
            $all_attrs = $before . ' ' . $after;
            if (preg_match('~\b(add_to_cart_button|ajax_add_to_cart|quick-view|quick_view)\b~i', $all_attrs)) return $tag;

            // 已有 target 的不重复添加
            if (stripos($all_attrs, 'target=') !== false) return $tag;

            return '<a' . $before . 'href=' . $q . $href . $q . $after . ' target="_blank" rel="noopener noreferrer">';
        }, $html);

        return $html;
    });
}, 20);