【问题标题】:Display different custom fields for different categories in WooCommerce在 WooCommerce 中为不同类别显示不同的自定义字段
【发布时间】:2016-08-04 06:09:31
【问题描述】:

我正在尝试在 WooCommerce 中为不同类别显示不同的自定义字段。

我在 content-single-product.php 模板文件中使用了以下条件语句:

      if(is_product_category('categoryname'))
    {
         // display my customized field
    }
else
{
do_action( 'woocommerce_after_single_product_summary' );
}

但这对我不起作用。

有没有更好的方法来解决这个问题?

谢谢。

【问题讨论】:

    标签: php wordpress woocommerce categories hook-woocommerce


    【解决方案1】:

    条件 is_product_category() 不适用于单个产品模板。在这种情况下,正确的条件是两个的组合:

    if ( is_product() && has_term( 'categoryname', 'product_cat' ) ) {
    
        // display my customized field
    
    } 
    ....
    

    您似乎正在尝试覆盖 content-single-product.php 模板。

    在你的 ELSE 语句中移动 woocommerce_single_product_summary 钩子不是一个好主意,只有当你不想显示 'categoryname' 产品 那 3 个钩子时功能:

     * @hooked woocommerce_output_product_data_tabs - 10
     * @hooked woocommerce_upsell_display - 15
     * @hooked woocommerce_output_related_products - 20
    

    您可以将代码 (在您的活动子主题或主题的 function.php 文件中) 嵌入到一个挂钩函数中,而不是(而不是在此处覆盖模板),使用这 2 个挂钩中更方便的一个:

    //In hook 'woocommerce_single_product_summary' with priority up to 50.
    
    add_action( 'woocommerce_single_product_summary', 'displaying_my_customized_field', 100);
    function displaying_my_customized_field( $woocommerce_template_single_title, $int ) { 
        if ( is_product() && has_term( 'categoryname', 'product_cat' ) ) {
    
            // echoing my customized field
    
        } 
    }; 
    

    // In hook 'woocommerce_after_single_product_summary' with priority less than 10
    
    add_action( 'woocommerce_after_single_product_summary', 'displaying_my_customized_field', 5);
    function displaying_my_customized_field( $woocommerce_template_single_title, $int ) { 
        if ( is_product() && has_term( 'categoryname', 'product_cat' ) ) {
    
            // echoing my customized field
    
        } 
    }; 
    

    【讨论】:

    • 非常感谢。覆盖 content-single-product.php 对我有用。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-29
    • 2021-10-06
    相关资源
    最近更新 更多