首页 > 解决方案 > 为特定产品类别向 Woocommerce 产品添加自定义字段

问题描述

我正在尝试将自定义字段添加到特定类别产品的单个产品页面。我遇到了条件逻辑问题。这是我到目前为止所得到的:

function cfwc_create_custom_field() {

global $product;
$terms = get_the_terms( $product->get_id(), 'product_cat' );

if (in_array("tau-ende", $terms)) {
    $args = array(
    'id' => 'custom_text_field_title',
    'label' => __( 'Custom Text Field Title', 'cfwc' ),
    'class' => 'cfwc-custom-field',
    'desc_tip' => true,
    'description' => __( 'Enter the title of your custom text field.', 'ctwc' ),);
    woocommerce_wp_text_input( $args );
    }}

该函数有效,但 if 语句无效。有谁知道我做错了什么?

标签: phpwordpresswoocommercecustom-taxonomytaxonomy-terms

解决方案


请尝试以下操作,使用遍历术语对象的 foreach 循环:

function cfwc_create_custom_field() {
    global $product;

    $terms = get_the_terms( $product->get_id(), 'product_cat' );

    // Loop through term objects
    foreach( $terms as $term ) {
        if ( "tau-ende" === $term->slug ) {
            woocommerce_wp_text_input( array(
                'id' => 'custom_text_field_title',
                'label' => __( 'Custom Text Field Title', 'cfwc' ),
                'class' => 'cfwc-custom-field',
                'desc_tip' => true,
                'description' => __( 'Enter the title of your custom text field.', 'ctwc' ),
            ) );
            break; // The term match, we stop the loop.
        }
    }
}

当一个术语匹配时,我们停止循环以只有一个自定义字段……它现在应该可以工作了。


推荐阅读