向 WooCommerce 我的帐户添加一个复选框 "Account details"

Add a checkbox to WooCommerce's My account "Account details"

在 WooCommerce 我的帐户 > 帐户详细信息部分,我已经能够使用以下代码添加一个复选框:

<div class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide woocommerce-form-row-newsletter">
    <label for="account_email" class="checkboxLabel"><?php esc_html_e( 'Receive Timenaut newsletter', 'woocommerce' ); ?>&nbsp;</label>
    <div class="woocommerce-MyAccount-settings">
        <?php
        woocommerce_form_field( 'mc4wp-subscribe', array(
            'type'          => 'checkbox',
            'class'         => array('form-row-wide')
            ), $value = 1);
        ?>
    </div>
</div>

我已将其添加到表单编辑-account.php,复选框显示正确,但很明显它没有保存值。

如何正确保存复选框值?


现在我还想将订阅者添加到 MailChimp 列表中。

你知道不用任何插件就可以将它发送到 Mailchimp 的方法吗?

要使您的复选框在“我的帐户”>“帐户详细信息”部分起作用并保存值,您可以使用以下方法:

// Remove "(optional)" label for this checkbox
add_filter( 'woocommerce_form_field' , 'remove_optional_fields_label', 10, 4 );
function remove_optional_fields_label( $field, $key, $args, $value ) {
    if( 'mc4wp-subscribe' === $key ) {
        $optional = '&nbsp;<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
        $field = str_replace( $optional, '', $field );
    }
    return $field;
}

// Display a custom checkbox in My Account > Account details
add_action( 'woocommerce_edit_account_form', 'display_edit_account_checkbox_field' );
function display_edit_account_checkbox_field() {
    woocommerce_form_field( 'mc4wp-subscribe', array(
        'type'  => 'checkbox',
        'class' => array('form-row-wide'),
        'label' => __( 'Receive Timenaut newsletter', 'woocommerce' ),
        'clear' => true,
    ), get_user_meta(get_current_user_id(), 'mc4wp-subscribe', true ) );

}

// Save checkbox field value for My Account > Account details
add_action( 'woocommerce_save_account_details', 'save_checkbox_value_to_account_details', 10, 1 );
function save_checkbox_value_to_account_details( $user_id ) {
    $value = isset( $_POST['mc4wp-subscribe'] ) ? '1' : '0';
    update_user_meta( $user_id, 'mc4wp-subscribe', $value );
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。测试和工作。

Now to register/unregister the subscriber in Mailchimp is another question and the rule on Stack OverFlow is one question at the time. So you will have to ask a new question for that.