我需要在唯一的选择字段中替换复选框字段,以显示在管理产品变体设置(仅适用于我的可变产品)中从子术语ID获得的产品类别术语名称。
因此woocommerce_wp_checkbox()
函数将由woocommerce_wp_select()
代替。
这是我的复选框的工作代码:
<?php
// Woocommerce Product meta
// Add Variation Settings
add_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );
// Save Variation Settings
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );
// Add fields
function variation_settings_fields( $loop, $variation_data, $variation ) {
// Characteristics
$args = array( 'type' => 'product', 'taxonomy' => 'product_cat', 'child_of' => 20 );
$categories = get_categories( $args );
foreach ($categories as $cat) {
woocommerce_wp_checkbox( array(
"id" => $cat->name .'_['. $variation->ID .']',
"label" => __(" " . $cat->name, "woocommerce" ),
"value" => get_post_meta( $variation->ID, $cat->name .'_', true ),
)
);
}
?>
<?php
}
// Save
function save_variation_settings_fields( $post_id ) {
// Characteristics
$args = array( 'type' => 'product', 'taxonomy' => 'product_cat', 'child_of' => 20 );
$categories = get_categories( $args );
foreach ($categories as $cat) {
$checkbox = isset( $_POST[$cat->name . '_'][ $post_id ] ) ? 'yes' : 'no';
update_post_meta( $post_id, $cat->name . '_', $checkbox );
}
}
?>
如何用下拉式(或最后是单选按钮)替换复选框?
我们非常感谢您的帮助。
答案 0 :(得分:0)
在您的实际代码中,存在一些错误,例如使用get_categories()
获取产品类别自定义分类法术语。相反,只需使用get_terms()
…
下面的代码将启用一个选择字段,而不是多个复选框。选择值保存正确。
重新访问的代码:
// Add Variation settings custom field
add_action( 'woocommerce_product_after_variable_attributes', 'add_product_category_variation_field', 11, 3 );
function add_product_category_variation_field( $loop, $variation_data, $variation ) {
// Get product categories that are child of term = 20
$terms = get_terms( array('taxonomy' => 'product_cat', 'child_of' => 20 ) );
$options = []; // Initializing
// Loop through each wp_term object and set term names in an array
foreach ($terms as $term) {
$term_name = __( $term->name, "woocommerce" );
$options[$term_name] = $term_name;
}
// The select field
woocommerce_wp_select( array(
'id' => '_product_category',
'name' => "_product_category_$loop",
'label' => __("product categories", "woocommerce" ),
'options' => $options,
'value' => get_post_meta( $variation->ID, '_product_category', true ),
) );
}
// Save Variation settings custom field
add_action( 'woocommerce_save_product_variation', 'save_product_category_variation_field', 11, 2 );
function save_product_category_variation_field( $variation_id, $loop ){
if( isset($_POST["_product_category_$loop"]) )
update_post_meta( $variation_id, '_product_category', esc_attr( $_POST["_product_category_$loop"] ) );
}
代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。