Wordpress Woocommerce中管理编辑产品的复选框自定义字段
我正在尝试将复选框添加到WooCommerce的“设置”选项卡(在“管理”面板中),并使用以下代码:Wordpress Woocommerce中管理编辑产品的复选框自定义字段,wordpress,checkbox,woocommerce,product,hook-woocommerce,Wordpress,Checkbox,Woocommerce,Product,Hook Woocommerce,我正在尝试将复选框添加到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(
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'] ) );
}
}
此代码显示复选框,但不保存更改。它只适用于一种产品。我猜
$post->ID
?更新后有问题……请尝试以下方法:
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 );
}
代码进入活动子主题(或活动主题)的function.php文件。经过测试,效果良好。试试这个
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 );
}
}
请提供屏幕截图,你想在哪里显示它。这是一个单一的产品吗?您确定使用的是正确的挂钩吗?请参阅此链接: