Woocommerce优惠券添加自定义复选框

时间:2017-02-25 18:11:12

标签: php wordpress checkbox woocommerce hook-woocommerce

我对functions.php中的这个简单功能已经足够了,让我为优惠券添加一个复选框。但是,一旦我保存/更新优惠券,我的复选框值(检查/未选中)就不会被提交(因此复选框始终未选中)。换句话说,当我更新/保存时,我无法让它在postmetas的meta_value列中将值更新为yes。复选框在那里,我只是不能使用它...非常令人沮丧!对我做错的任何消息,请:)

function add_coupon_revenue_dropdown_checkbox() { 
$post_id = $_GET['post'];

woocommerce_wp_checkbox( array( 'id' => 'include_stats', 'label' => __( 'Coupon check list', 'woocommerce' ), 'description' => sprintf( __( 'Includes the coupon in coupon check drop-down list', 'woocommerce' ) ) ) );

$include_stats = isset( $_POST['include_stats'] ) ? 'yes' : 'no';

update_post_meta( $post_id, 'include_stats', $include_stats );

do_action( 'woocommerce_coupon_options_save', $post_id );

}add_action( 'woocommerce_coupon_options', 'add_coupon_revenue_dropdown_checkbox', 10, 0 ); 

我试图影响的部分是:

可湿性粉剂内容/插件/ woocommerce /包括/管理/元盒/类-WC-元箱优惠券data.php

1 个答案:

答案 0 :(得分:5)

您的代码的问题在于您试图在为其生成html的同一函数中保存复选框的值。这不行。您需要将当前函数分解为两个部分,这两个部分在两个不同的WooCommerce挂钩上运行。

第一个是显示实际的复选框:

function add_coupon_revenue_dropdown_checkbox() { 
    woocommerce_wp_checkbox( array( 'id' => 'include_stats', 'label' => __( 'Coupon check list', 'woocommerce' ), 'description' => sprintf( __( 'Includes the coupon in coupon check drop-down list', 'woocommerce' ) ) ) );
}
add_action( 'woocommerce_coupon_options', 'add_coupon_revenue_dropdown_checkbox', 10, 0 );

第二种是在处理提交的表单时保存复选框的值。

function save_coupon_revenue_dropdown_checkbox( $post_id ) {
    $include_stats = isset( $_POST['include_stats'] ) ? 'yes' : 'no';
    update_post_meta( $post_id, 'include_stats', $include_stats );
}
add_action( 'woocommerce_coupon_options_save', 'save_coupon_revenue_dropdown_checkbox');