【问题标题】:Add a custom field to Woocommerce products for a specific product category为特定产品类别向 Woocommerce 产品添加自定义字段
【发布时间】:2019-02-20 19:23:57
【问题描述】:

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

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 语句无效。有谁知道我做错了什么?

【问题讨论】:

    标签: php wordpress woocommerce custom-taxonomy taxonomy-terms


    【解决方案1】:

    尝试以下方法,使用 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.
            }
        }
    }
    

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

    【讨论】:

      【解决方案2】:
      get_the_terms(id, taxonomy)
      

      此函数返回一个WP_Term 对象数组,而不是术语的字符串名称。因此使用了 in_array 函数的 if 条件。

      如果你想检查给定的名字是否在条款中,你可以这样做 -

      $cond = false;
      foreach($terms as $term) {
          if ($term->slug == "tau-ende"){ // You can also match using $term->name
              $cond = true;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-16
        • 1970-01-01
        • 2015-07-12
        • 2023-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多