为特定产品类别向Woocommerce产品添加自定义字段 [英] Add a custom field to Woocommerce products for a specific product category
本文介绍了为特定产品类别向Woocommerce产品添加自定义字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将特定类别产品的自定义字段添加到单个产品页面.我在使用条件逻辑时遇到了问题. 这是到目前为止我得到的:
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 );
}}
该功能有效,但if语句无效.有人知道我在做什么错吗?
The function works but not the if-statement. Does anyone have an idea what I'm doing wrong?
推荐答案
尝试使用以下遍历术语对象的foreach循环尝试以下操作:
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.
这篇关于为特定产品类别向Woocommerce产品添加自定义字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文