问题
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