簡體   English   中英

為特定產品類別的 Woocommerce 產品添加自定義字段

[英]Add a custom field to Woocommerce products for a specific product category

我正在嘗試將自定義字段添加到特定類別中產品的單個產品頁面。 我在條件邏輯方面遇到了問題。 這是我到目前為止所得到的:

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 語句無效。 有誰知道我做錯了什么?

請嘗試以下操作,使用 foreach 循環遍歷 term 對象:

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.
        }
    }
}

當一個術語匹配時,我們停止循環以只有一個自定義字段......它現在應該可以工作了。

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM