Add a custom field to Woocommerce products for a specific product category

[亡魂溺海] 提交于 2019-12-11 00:37:44

问题


I'm trying to add a custom field to the single product page for products in a specific category. I'm having problems with the conditional logic tho. This is what I've got so far:

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

The function works but not the if-statement. Does anyone have an idea what I'm doing wrong?


回答1:


Try the following instead, using a foreach loop iterating through term objects:

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

When a term match, we stop the loop to have just one custom field… It should work now.




回答2:


get_the_terms(id, taxonomy)

This function returns an array of WP_Term objects and not string names of the terms. Hence the if condition, which uses in_array function.

If you want to check whether the given name is in the terms, you can probably do it like this -

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


来源:https://stackoverflow.com/questions/54793842/add-a-custom-field-to-woocommerce-products-for-a-specific-product-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!