php - 为特定产品类别向 Woocommerce 产品添加自定义字段
问题描述
我正在尝试将自定义字段添加到特定类别产品的单个产品页面。我遇到了条件逻辑问题。这是我到目前为止所得到的:
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 循环:
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.
}
}
}
当一个术语匹配时,我们停止循环以只有一个自定义字段……它现在应该可以工作了。
推荐阅读
- php - 如何在 php codeigniter 上制作动态表
- ios - 添加应用程序未继续
- javascript - 通过参数 JS 对嵌套对象进行排序
- prolog - Prolog If 语句事实
- python - Is os.path.isfile always the opposite of os.path.isdir for an existing file system object?
- android - "Shrink" CardView while scrolling in another view
- c++ - Vector push_back changes values of previous elements.
- python - What should the generator return if it is used in a multi-input/output Keras model built with functional API?
- javascript - Append autocomplete selection to textarea
- java - Beam: writing per window element count with window boundaries