You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让WooCommerce分类页与商品页商品名称替换为customname1字段值

实现商品分类页与详情页的商品标题替换

要在商品分类页(含产品标签归档页)和商品详情页,用自定义字段customname1覆盖商品标题(仅当字段存在时生效),可以添加以下代码到主题的functions.php文件或自定义插件中:

// 替换商品分类页与详情页的标题
function replace_product_title_with_customname1( $title, $post_id ) {
    // 仅针对WooCommerce产品,且在目标页面生效
    if ( get_post_type( $post_id ) === 'product' && ( is_product() || is_product_category() || is_product_tag() ) ) {
        $custom_name = get_post_meta( $post_id, 'customname1', true );
        // 自定义字段非空时替换标题,否则保留原标题
        if ( ! empty( $custom_name ) ) {
            return $custom_name;
        }
    }
    return $title;
}
add_filter( 'the_title', 'replace_product_title_with_customname1', 10, 2 );

代码说明

  • 用the_title钩子拦截标题输出,适配WordPress与WooCommerce的标题渲染逻辑
  • 通过get_post_type确保只处理产品类型内容
  • 条件判断is_product()(商品详情页)、is_product_category()(商品分类页)、is_product_tag()(商品标签页),覆盖所有产品归档类页面
  • 读取customname1字段后,仅在字段非空时替换原标题,避免空值覆盖

整合已有代码(可选)

如果想把购物车/结账页的替换逻辑与新代码合并,可写成统一函数:

function custom_product_title_replacement( $title, $param ) {
    // 处理购物车、结账页的标题替换
    if ( is_checkout() || is_cart() ) {
        $product_id = $param['product_id'];
        $custom_name = get_post_meta( $product_id, 'customname1', true );
        return ! empty( $custom_name ) ? $custom_name : $title;
    }
    // 处理分类页、详情页的标题替换
    if ( is_int( $param ) && get_post_type( $param ) === 'product' && ( is_product() || is_product_category() || is_product_tag() ) ) {
        $custom_name = get_post_meta( $param, 'customname1', true );
        return ! empty( $custom_name ) ? $custom_name : $title;
    }
    return $title;
}
// 挂载购物车项标题钩子
add_filter( 'woocommerce_cart_item_name', 'custom_product_title_replacement', 10, 2 );
// 挂载全局标题钩子
add_filter( 'the_title', 'custom_product_title_replacement', 10, 2 );

这样就能在所有目标页面统一实现自定义标题替换效果。

内容的提问来源于stack exchange,提问作者Qwertzui11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 01:22:06