[英]Add a custom field to Woocommerce products for a specific product category
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.该函数有效,但 if 语句无效。 Does anyone have an idea what I'm doing wrong?有谁知道我做错了什么?
Try the following instead, using a foreach loop iterating through term objects:请尝试以下操作,使用 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.
}
}
}
When a term match, we stop the loop to have just one custom field… It should work now.当一个术语匹配时,我们停止循环以只有一个自定义字段......它现在应该可以工作了。
get_the_terms(id, taxonomy)
This function returns an array of WP_Term
objects and not string names of the terms.此函数返回WP_Term
对象的数组,而不是术语的字符串名称。 Hence the if condition, which uses in_array
function.因此使用in_array
函数的 if 条件。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.