[英]Checkbox custom fields for admin edit product in Woocommerce
I'm trying to add checkbox to settings tab in WooCommerce (in admin panel) and use this code: 我试图在WooCommerce(在管理面板中)的“设置”标签中添加复选框,并使用以下代码:
add_action( 'woocommerce_product_options_general_product_data', 'wc_custom_add_custom_fields' );
function wc_custom_add_custom_fields() {
global $post;
woocommerce_wp_checkbox(array(
'id' => 'is_gift',
'label' => __('Gift', 'woocommerce' ),
'description' => __( 'Add gift label', 'woocommerce' ),
'value' => get_post_meta($post->ID, 'is_gift', true)
));
}
add_action( 'woocommerce_process_product_meta', 'wc_custom_save_custom_fields' );
function wc_custom_save_custom_fields() {
global $post;
if (!empty($_POST['is_gift'])) {
update_post_meta( $post->ID, 'is_gift', esc_attr( $_POST['is_gift'] ) );
}
}
This code showing checkbox, but not saving changes. 此代码显示复选框,但不保存更改。 It works only for one product.
它仅适用于一种产品。 I guess something wrong with
$post->ID
? 我猜
$post->ID
吗?
Updated … Try this instead: 已更新…尝试以下方法:
add_action( 'woocommerce_product_options_general_product_data', 'wc_custom_add_custom_fields' );
function wc_custom_add_custom_fields() {
global $post;
$input_checkbox = get_post_meta( $post->ID, 'is_gift', true );
if( empty( $input_checkbox ) ) $input_checkbox = '';
woocommerce_wp_checkbox(array(
'id' => 'is_gift',
'label' => __('Gift', 'woocommerce' ),
'description' => __( 'Add gift label', 'woocommerce' ),
'value' => $input_checkbox,
));
}
add_action( 'woocommerce_process_product_meta', 'wc_custom_save_custom_fields' );
function wc_custom_save_custom_fields($post_id) {
$_custom_text_option = isset( $_POST['is_gift'] ) ? 'yes' : '';
update_post_meta( $post_id, 'is_gift', $_custom_text_option );
}
Code goes in function.php file of your active child theme (or active theme). 代码进入您的活动子主题(或活动主题)的function.php文件中。 Tested and works.
经过测试和工作。
try this 尝试这个
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
function woo_add_custom_general_fields() {
global $woocommerce, $post;
$checkbox_value = get_post_meta( $post->ID, 'is_gift', true );
if( empty( $checkbox_value ) ){
$checkbox_value = '';
}
woocommerce_wp_checkbox(
array(
'id' => 'is_gift',
'label' => __('Gift', 'woocommerce' ),
'description' => __( 'Add gift label', 'woocommerce' ),
'value' => $checkbox_value,
)
);
}
// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields_save( $post_id ){
// Checkbox
$_checkbox = $_POST['is_gift'];
if (isset( $_checkbox )){
update_post_meta( $post_id, '_is_gift', $_checkbox );
}
}
Sorry anyone. 不好意思 The reason was in my server configuration (I've delete tmp folder), so all codes below working on normal hosting.
原因是在我的服务器配置中 (我已经删除了tmp文件夹),因此下面的所有代码都可以在正常主机上正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.