在前端各处自定义 WooCommerce 产品名称

Customize WooCommerce Product Name everywhere in Frontend

我想在 Woocommerce 上出售反向链接。为此,我需要隐藏我保存在 WooCommerce 产品标题中的域名。有没有一种方法可以操纵所有显示产品名称的地方,比如商店循环、结帐页面,基本上无处不在,这样客户就看不到 domain.com 而是看到 d****n.com?也许有一个过滤器或钩子或其他东西。

我已经在这里试过了Change related product names via filter in WooCommerce

但它在购物车、结账台和忍者桌上不起作用。

要隐藏 WooCommerce 产品名称(或标题),请使用以下内容:

add_filter( 'the_title', 'hide_product_title', 10, 2 );
function hide_product_title( $title, $post_id ) {
    global $woocommerce_loop;

    if ( ! is_admin() && ! empty($woocommerce_loop) ) {
        $title = '';
    }
    return $title;
}

add_filter( 'woocommerce_product_get_name', 'hide_product_name', 10, 2 );
add_filter( 'woocommerce_product_variation_get_name', 'hide_product_name', 10, 2 );
function hide_product_name( $name, $product ) {
    if ( ! is_admin() ) {
        $name = '';
    }
    return $name;
}

现在要在任何地方隐藏作为产品标题包含的域名,请使用以下内容(用星号替换域名,第一个和最后一个字符除外) :

// Custom function to replace a string (domain name) with a repeating character (a star by default)
function hide_domain_name( $string, $repl_char = '*' ) {
    $index_needle = strpos($string, '.');
    $replacement  = str_repeat($repl_char, ($index_needle > 2 ? $index_needle - 2 : strlen($string) - 1));
    return substr_replace($string, $replacement, 1) . substr($string, ($index_needle > 2 ? $index_needle - 1 : strlen($string) - 1));
}

add_filter( 'the_title', 'hide_product_title', 10, 2 );
function hide_product_title( $title; $post_id ) {
    global $woocommerce_loop;

    if ( ! is_admin() && ! empty($woocommerce_loop) ) {
        $title = hide_domain_name( $title );
    }
    return $title;
}

add_filter( 'woocommerce_product_get_name', 'hide_product_name', 10, 2 );
add_filter( 'woocommerce_product_variation_get_name', 'hide_product_name', 10, 2 );
function hide_product_name( $name, $product ) {
    if ( ! is_admin() ) {
        $name = hide_domain_name( $name );
    }
    return $name;
}

Don't forget to make custom permalinks for your products, as the product title (domain name) should appear in it.

代码进入活动 child 主题(或活动主题)的 functions.php 文件。已测试并有效。