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

axe*_*a82 0 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 ); 
Run Code Online (Sandbox Code Playgroud)

我要影响的部分是:

wp-content / plugins / woocommerce / includes / admin / meta-boxes / class-wc-meta-box-coupon-data.php

小智 6

代码的问题在于,您试图将复选框的值保存在为其生成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 );
Run Code Online (Sandbox Code Playgroud)

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

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');
Run Code Online (Sandbox Code Playgroud)