Add a newsletter subscription checkbox form on WooCommrece Register Page

左心房为你撑大大i 提交于 2019-12-01 12:57:47

The SendGrid plugin is not anymore maintained since a while (so it seems really outdated).

Updated: Now to add a checkbox for a news letter subscription in Woocommerce registration form (and on My account > Account details section), you will use the following:

// Remove "(optional)" label for this checkbox
add_filter( 'woocommerce_form_field' , 'remove_optional_custom_field_label', 10, 4 );
function remove_optional_custom_field_label( $field, $key, $args, $value ) {
    if( 'receive_newsletter' === $key && is_wc_endpoint_url( 'edit-account' ) ) {
        $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_register_form', 'add_account_newsletter_checkbox_field' );
add_action( 'woocommerce_edit_account_form', 'add_account_newsletter_checkbox_field' );
function add_account_newsletter_checkbox_field() {
    woocommerce_form_field( 'receive_newsletter', array(
        'type'  => 'checkbox',
        'class' => array('form-row-wide'),
        'label' => __( 'Subscribe to our newsletter?', 'woocommerce' ),
        'clear' => true,
    ), get_user_meta(get_current_user_id(), 'receive_newsletter', true ) );

}


// Save registration checkbox field value
add_action( 'woocommerce_created_customer', 'save_account_registration_field' );
function save_account_registration_field( $customer_id ) {
    $value = isset( $_POST['receive_newsletter'] ) ? '1' : '0';
    update_user_meta( $customer_id, 'receive_newsletter', $value );

}

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

Code goes in functions.php file of your active child theme (or active theme). Tested and works.


1) On WooCommerce Registration form:

2) On My account > Account details (section):

Now as this your plugin is outdated and as the rule on StackOverFlow is one question at the time, you will have to handle the Sendgrid Newsletter integration (as it's anyway something too broad).

I don't really get what you are asking. But I do have a few things to point you in the right direction.

  1. your jQuery should be in it's own file which is loaded using wp_enqueue_script
  2. Check if a user is loggedin using is_user_logged_in
  3. Pass that status to JS using wp_localize_script
  4. you now have the login status available in a JS variable.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!