如何设置在产品woocommerce中始终选中的复选框?

时间:2019-01-15 11:12:02

标签: php wordpress woocommerce

如何设置一个始终选中的复选框?我正在使用“ Woocommerce产品费用”插件来向产品收取费用。它有一个复选框,选中该复选框时,它会计算购物车中添加的每种产品的费用。我要实现的是将此复选框设置为始终针对每个产品进行检查,但我找不到正确的方法。我添加了$ checked,但是什么也没发生...

这是我的代码的一部分:

    // Check Box - Fee Multiply Option
    woocommerce_wp_checkbox( array( 
        'id'=> 'product-fee-multiplier[' . $variation->ID . ']', 
        'label' => __('Multiply Fee by Quantity', 'woocommerce-product-fees' ),
        'value' => get_post_meta( $variation->ID, 'product-fee-multiplier', true ), 
        'wrapper_class' => "product-fee-multiplier" , 
        'required'  => true
    ), $checked );

    do_action( 'wcpf_add_variation_settings' );

}

public function save_variation_settings_fields( $post_id ) {
    $another_field_updated = false;
    // Text Field - Fee Name
    $product_fee_name_text_field = $_POST['product-fee-name'][ $post_id ];
        if( ! empty( $product_fee_name_text_field ) || get_post_meta( 
        $post_id, 'product-fee-name', true ) != '' ) {
            update_post_meta( $post_id, 'product-fee-name', esc_attr( $product_fee_name_text_field ) );
            $another_field_updated = true;
        }

2 个答案:

答案 0 :(得分:1)

在使用Woocommerce woocommerce_wp_checkbox()表单字段函数时,如果希望始终选中默认复选框,则将使用'cbvalue'数组参数,例如:

// Check Box - Fee Multiply Option
woocommerce_wp_checkbox( array( 
    'id'            => 'product-fee-multiplier[' . $variation->ID . ']', 
    'label'         => __('Multiply Fee by Quantity', 'woocommerce-product-fees' ),
    'value'         => get_post_meta( $variation->ID, 'product-fee-multiplier', true ), 
    'cbvalue'       => get_post_meta( $variation->ID, 'product-fee-multiplier', true ), 
    'wrapper_class' => "product-fee-multiplier" , 
    'required'      => true
), $checked );

do_action( 'wcpf_add_variation_settings' );

这将使您始终选中目标复选框。

答案 1 :(得分:-1)

如果您尝试阅读文档,可以看到该函数woocommerce_wp_checkbox()在内部具有不同的参数,并在其中使用了checked()函数。 因此,如果value = cbvalue,则添加检查。 另外,您可以使用参数custom_attributes添加自定义。 因此,您有两种方法:

woocommerce_wp_checkbox( array( 
    'id'=> 'product-fee-multiplier[' . $variation->ID . ']', 
    'label' => __('Multiply Fee by Quantity', 'woocommerce-product-fees' ),
    'value' => get_post_meta( $variation->ID, 'product-fee-multiplier', true ), 
    'cbvalue' => get_post_meta( $variation->ID, 'product-fee-multiplier', true ), 
    'wrapper_class' => "product-fee-multiplier" , 
    'required'  => true
));

OR:

woocommerce_wp_checkbox( array( 
    'id'=> 'product-fee-multiplier[' . $variation->ID . ']', 
    'label' => __('Multiply Fee by Quantity', 'woocommerce-product-fees' ),
    'value' => get_post_meta( $variation->ID, 'product-fee-multiplier', true ), 
    'custom_attributes' => 'checked',
    'wrapper_class' => "product-fee-multiplier" , 
    'required'  => true
));