Integrating New User Approve WP Plugin with WooCommerce

I originally wrote this guide to work with the WP Approve User plugin, however that plugin appears to not be well maintained any longer, so this is a similar guide for the “New User Approve” plugin instead.

When building an ecommerce website with wholesale functions, there were two key modifications that needed to be completed to WooCommerce in order to make it work for the customer’s business:

  1. New users (distributors) must be able to be moderated by an admin so the site owner can choose to approve or reject them as distributors of their product
  2. Visitors must be blocked from seeing pricing and adding items to their cart until they have been registered and approved

Catalog Visibility

In order to hide pricing and block adding items to the cart for users that are not logged in, WooCommerce already has a fantastic (albeit paid) plugin called Catalog Visibility Options. This plugin worked perfectly for what we needed using just a couple drop downs. What it doesn’t do (nor does it claim to do) is manage user registrations – the other half of the puzzle.

catalog_visibility

User Moderation

Although the New User Approve plugin is a well devised addition to WordPress, the custom registration and login capabilities of WooCommerce do not play nicely with plugins that use registration and login hooks. Additionally, WooCommerce has some great email notifications built in, whereas New User Approve has its own designed notifications.

Upon installing New User Approve, the user registration process goes like this:

  1. User registers
  2. WooCommerce automatically logs them in [PROBLEM]
  3. If the user logs out, they can’t get in again since they have yet to be approved

Removing / working around auto login

At this point, the registration is not obeying the New User Approve plugin when it automatically logs the user in, but the login form *is* obeying the hooks provided by New User Approve. In order to fix this automatic login during registration, I wrote the following hooks to be placed in your theme’s functions.php file:

function ws_new_user_approve_autologout(){
       if ( is_user_logged_in() ) {
                $current_user = wp_get_current_user();
                $user_id = $current_user->ID;

                if ( get_user_meta($user_id, 'pw_user_status', true )  === 'approved' ){ $approved = true; }
		else{ $approved = false; }


		if ( $approved ){ 
			return $redirect_url;
		}
                else{ //when user not approved yet, log them out
			wp_logout();
                        return add_query_arg( 'approved', 'false', get_permalink( get_option('woocommerce_myaccount_page_id') ) );
                }
        }
}
add_action('woocommerce_registration_redirect', 'ws_new_user_approve_autologout', 2);

function ws_new_user_approve_registration_message(){
        $not_approved_message = '<p class="registration">Send in your registration application today!<br /> NOTE: Your account will be held for moderation and you will be unable to login until it is approved.</p>';

        if( isset($_REQUEST['approved']) ){
                $approved = $_REQUEST['approved'];
                if ($approved == 'false')  echo '<p class="registration successful">Registration successful! You will be notified upon approval of your account.</p>';
                else echo $not_approved_message;
        }
        else echo $not_approved_message;
}
add_action('woocommerce_before_customer_login_form', 'ws_new_user_approve_registration_message', 2);

This accomplishes two things. It takes care of making sure the user is logged out immediately after WooCommerce logs them in, and second it notifies the user that their registration completed successfully, but they cannot login until they have been approved. The successful registration notification was never needed by WooCommerce because it normally just logs them right into their account – something we can’t do in this case.

Notification Emails

Please note, the New User Approve plugin does not appear to have an option to disable or suppress its built in emails. This means that you will need to either use their emails and *not* implement the code below, or edit the New User Approve plugin’s code to disable their emails. I do not recommend the latter because upon update, it will be overwritten.

New User Approve has a couple of Action Hooks we can plug in to for sending out notification emails. Although I didn’t make use of the unapprove hook, you can easily duplicate my existing work to make that happen if you wish.

You will want to first do as WooCommerce suggests: “For more advanced control copy woocommerce/templates/emails/ to yourtheme/woocommerce/emails/.”

Once you’ve’ copied the templates for adjustment, head to yourtheme/woocommerce/emails and edit the customer-new-account.php file.

Note that with WooCommerce 3.0 and newer you can now do this from the UI by going to WooCommerce > Settings > Emails and clicking the cog icon to the far right of the “New account” email template in the list. Click the “Copy file to theme” button. Once done, you can then click “View Template” to edit the file and make your changes.

You will want to add to this template something that indicates that the account has been held for moderation. This way, the email template is sent out to indicate to them that they cannot login immediately.


We also need an email template that is sent when the user is approved by an admin. In yourtheme/woocommerce/emails, create a file called customer-account-approved.php and paste the following in:

<?php if (!defined('ABSPATH')) exit; ?>

<?php do_action('woocommerce_email_header', $email_heading); ?>

<p><?php echo sprintf(__("Good news! Your account has been approved. You can now login here: %s.", 'woocommerce'), make_clickable(esc_url( wc_get_page_permalink('myaccount')))); ?></p>

<ul>
        <li><?php echo sprintf(__('Username: %s', 'woocommerce'), $user_login); ?></li>
        <li><?php echo sprintf(__('Password: %s', 'woocommerce'), $user_pass); ?></li>
</ul>

<p><?php echo sprintf(__("Thanks for registering with %s!", 'woocommerce'), $blogname); ?></p>

<div style="clear:both;"></div>

<?php do_action('woocommerce_email_footer'); ?>

Now that we’ve got our email templates ready to roll, we need an action hook to send off the approval email when the admin clicks “approve” for any user. Again, enter the following in your theme’s functions.php file:

//Email Notifications
//Content parsing borrowed from: woocommerce/classes/class-wc-email.php
function ws_new_user_approve_send_approved_email($user_id){

	global $woocommerce;
	//Instantiate mailer
	$mailer = $woocommerce->mailer();

        if (!$user_id) return;

        $user = new WP_User($user_id);

        $user_login = stripslashes($user->user_login);
        $user_email = stripslashes($user->user_email);
        $user_pass  = "As specified during registration";

        $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);

        $subject  = apply_filters( 'woocommerce_email_subject_customer_new_account', sprintf( __( 'Your account on %s has been approved!', 'woocommerce'), $blogname ), $user );
        $email_heading  = "User $user_login has been approved";

        // Buffer
        ob_start();

        // Get mail template
        woocommerce_get_template('emails/customer-account-approved.php', array(
                'user_login'    => $user_login,
                'user_pass'             => $user_pass,
                'blogname'              => $blogname,
                'email_heading' => $email_heading
       ));

        // Get contents
        $message = ob_get_clean();

        // Send the mail
        woocommerce_mail( $user_email, $subject, $message, $headers = "Content-Type: text/htmlrn", $attachments = "" );
}
add_action('new_user_approve_approve_user', 'ws_new_user_approve_send_approved_email', 10, 1);

function ws_new_user_approve_send_denied_email($user_id){
        return;
}
add_action('new_user_approve_deny_user', 'ws_new_user_approve_send_denied_email', 10, 1);

As I mentioned above, you can do the very same with denied users. If you wish to do this, use the same code from the approve function and copy/paste it to the denied function that currently returns nothing, then create another email template like above.


One reader of this post, Maya, had a need to lock down registration by preventing auto-login when an order is placed. Typically in wholesale account environments, orders can’t be placed until an account is registered and approved, however Maya’s scenario was a bit different. If you also require that functionality, Maya was kind enough to share the code. Note that I haven’t used this code myself, so I won’t be of much help if you have trouble with it.

function wc_custom_redirect_after_purchase() {
  global $woocommerce;
  if ( is_checkout() && ! empty( $wp->query_vars['order-received']) && ws_new_user_approve_autologout() ) {
    return apply_filters( 'woocommerce_get_return_url', $return_url, $order );
    wp_logout();
  }
}
add_action( 'woocommerce_thankyou', 'wc_custom_redirect_after_purchase' );

I hope this helps anyone else trying to use the New User Approve plugin! Please leave your comments and suggestions along with any problems you may have encountered.

If you need a hand integrating this code on your site, send us a message: we’d love to help make that happen.

Jordan is a computer, security, and network systems expert and a lover of all things web and tech. Jordan consults with project management for software companies. Jordan is a founder and managing partner at Websavers Inc.

47 Comments

  1. Mike devis on August 7, 2018 at 3:36 am

    Helo, Can please tell me how to make an interface to add the fields in registration page directly? Like they are offering https://codecanyon.net/item/woocommerce-registration-plugin-add-custom-registration-fields/20515456

  2. Angelika on July 21, 2018 at 9:37 am

    Logout for me isn’t working. WordPress 4.9.7 and WooCommerce 3.4.3. Any ideas?

  3. Michael on July 20, 2018 at 3:32 pm

    Auto logout isn’t working for me (WP 4.9.7 + WC 3.4.3).

  4. Vikas Shukla on July 16, 2018 at 7:27 am

    How can we disable the default fron New User Approve plugin? or how we can apply woocommerce template to this one?

    Thanks

    • Jordan Schelew on July 26, 2018 at 11:08 pm

      See all the comments on this page for possible solutions to this.

  5. Costy on July 8, 2018 at 5:00 pm

    Thanks for this snippet, but can we redirect non approved user to a specific page?
    How can we achieve that?

    • Jordan Schelew on July 26, 2018 at 11:08 pm

      Yes, in the function called “ws_new_user_approve_autologout” on line 16 of that code block, you’ll see the call to “add_query_arg” — the last parameter of that function is the URL you wish to redirect to.

  6. Marco Vito on March 15, 2018 at 5:53 am

    Hy thanks for sharing!
    I follow all you instruction but i have two question:
    1- Why i have 2 email send to customer after approve? ( one is from plug inn and second from this personalization)

    2 Sorry but I do not understand the way for send un-approved mail

    Thanks for answer me

    • Jordan Schelew on April 6, 2018 at 5:30 pm

      Hey Marco,

      Further down in these comments someone else brought up this issue with duplicate emails. Because there appears to be no way to suppress the built in New User Approve email (other than commenting out their code, which will get overwritten on update), you’ll have to simply comment out the custom email system that was part of this guide. Perhaps the New User Approve folks will add an option to suppress their email in the future. If you find a way to do this, please do update here!

      -Jordan

  7. David on March 12, 2018 at 10:32 am

    thanks!

  8. Beau on February 13, 2018 at 3:23 pm

    I set this up but no email was set when the new user was approved.

    I followed your walkthrough correctly. Have you got any clues as to why the email won’t get sent out? Woocommerce new user email doesn’t send either.

    • Jordan Schelew on February 14, 2018 at 12:26 am

      Hey Beau,

      If the built in WooComm New User email doesn’t send, then you probably have overall email deliverability issues with WordPress. Take a look here for possible solutions: https://websavers.ca/configure-form-successful-email-delivery

      It’s not exactly a form, but the solutions are often much the same. You configure WooCommerce to send emails from a particular address, so matching that setting up with the From field config described in the above article will help. Similarly checking and potentially adjusting your SPF record is important. If you’re still having trouble, ask your web host to help! If they’re no help, then I might suggest moving hosting to us 🙂

  9. Eric Groft on January 12, 2018 at 6:55 pm

    Thank you. I’m using this for a client and have given you attribution in the code, but please let me know if you would like some further attribution.

    • Jordan Schelew on January 12, 2018 at 11:36 pm

      Thanks Eric, I’m glad to hear you’ve found it useful! If you’re ever in the market for an alternative (or specifically Canadian) VPS provider, come say hi again 🙂

  10. Mike on November 10, 2017 at 7:33 am

    Hi Jordan, thanks for this, really useful. The function ws_new_user_approve_autologout in ‘Removing / working around auto login’ was causing a ‘headers already sent’ error for me. I replaced the line:
    return get_permalink(woocommerce_get_page_id(‘myaccount’)) . “?approved=false”;
    with
    return get_permalink( get_option(‘woocommerce_myaccount_page_id’) ) . “?approved=false”;
    as used here – https://docs.woocommerce.com/document/display-my-account-link-in-a-template-file/ – and this fixed it for me

    • Mike on November 10, 2017 at 8:06 am

      I also realised I was having an issue with the GET variable as my permalink settings meant it was the 2nd GET variable used in the URL. This is better I think:
      return add_query_arg( ‘approved’, ‘false’, get_permalink( get_option(‘woocommerce_myaccount_page_id’) ) );

      • Jordan Schelew on November 10, 2017 at 9:34 am

        That’s definitely a cleaner way to do that; thanks for the feedback! I’ve updated the article accordingly.

        • Mike on November 13, 2017 at 4:12 pm

          This stops the user approved email being sent by the New User Approve plugin:
          add_filter( ‘new_user_approve_approve_user_message’, ‘__return_false’ );

          Also Woocommerce 3 is giving some notices – you should use wc_get_template instead of woocommerce_get_template and wc_mail instead of woocommerce_mail

  11. John Q on October 11, 2017 at 4:53 pm

    This is a great article! However, I have a couple questions: I installed the plugin and added the code to my functions.php so that the user is immediately logged out. Once a user registers, it goes to a 404 page. 1. What can I do to prevent this? 2. Is there a way to display a message or have a popup showing saying that the new acct is pending for approval? And 3. How can I ask for more information like name, last, phone, company name, etc?

    • Jordan Schelew on October 11, 2017 at 5:15 pm

      Thanks John!

      1. What’s the URL of the 404 page? I suspect the change I made last week might have caused this.
      2. This *should* be the case already if it were to redirect to the right page. So if we solve #1, it should solve #2 as well.
      3. That’s out of scope for this solution, but you can add more fields to the registration page with additional action hooks. I’ve used this guide before to great success: https://www.proy.info/custom-fields-to-woocommerce-registration-form/

      • pluggedbean on November 3, 2017 at 8:24 am

        Hi Jordan, Again thanks for the workaround but I’m also getting a 404 for the redirect, It looks like the redisrect is duplicating the url ? MYDOMAIN/my-account/ahref=http:/MYDOMAIN/my-account/rel=nofollowhttp:/MYDOMAIN/my-account/a?approved=false

    • pluggedbean on November 3, 2017 at 9:34 am

      I replaced
      make_clickable(esc_url( wc_get_page_permalink(‘myaccount’)))

      with

      get_permalink(woocommerce_get_page_id(‘myaccount’))

      and it seems to work fine now , hope that helps John Q

      • Jordan Schelew on November 3, 2017 at 2:27 pm

        Thanks for confirming that fix! I’ve updated the code to match. The only make_clickable part that remains is in the email template.

  12. Chris Mundy on October 3, 2017 at 7:45 am

    Hi Jordan,

    I’m currently researching this option for a client so thanks for a great article.

    In the paragraph title “Removing / working around auto login” you’ve mentioned ‘WP Approve User plugin’ in the text, shouldn’t this be ‘New User Approve WP Plugin’?

    Chris

  13. Ashley on October 1, 2017 at 4:35 am

    Hi, can anyone help me on my problem?

    I tried the code above where it log out the user and then redirect to my-account page. But it’s not working. It’s log out me and redirect me to on my registration page after registration.

    • Jordan Schelew on October 1, 2017 at 11:23 am

      Hey Ashley; You can’t redirect to the my-account page (and get the my account page) because it just logged the user out. You can’t view the my account page until you’re logged in, which this set-up is intended to prevent. Therefore you *will* always end up seeing the login page which, if your settings in WooCommerce are configured as such, will also be the registration page.

  14. George Pattihis on September 18, 2017 at 11:02 pm

    Great article, exactly what I was looking for and works perfectly. I don’t mind sending out two emails when status change, but if you have a permanent solution please share.

    Just a notice, in customer-account-approved.php instead of :

    get_permalink(woocommerce_get_page_id(‘myaccount’))

    you can use:

    make_clickable(esc_url( wc_get_page_permalink(‘myaccount’)))

    so that the link is clickable directly in the email message. Other than that, thank you!

    • Jordan Schelew on October 1, 2017 at 11:19 am

      Thanks George! I’ve updated the guide above accordingly 🙂

  15. Carl on September 18, 2017 at 10:25 am

    commnet out the wpmail function on booth the denie and approved function innew-user-approved.php

    • Jordan Schelew on September 18, 2017 at 11:37 am

      Hey Carl,

      Yes this is a possible solution, though when you update the plugin the changes will be ovewritten. This is why I think the developer should provide an action hook for this.

      For those looking to do this, simply comment out line 573 (currently) as shown here, but obviously in your live code equivalent of this file.

      Since this function uses wp_mail, it looks like this built in WordPress filter could help as well. Anyone willing to try this out? I’m guessing you could do something like this:

      add_filter( 'wp_mail', 'ws_wp_mail_filter_override_new_user_approve_message' );
      function ws_wp_mail_filter_override_new_user_approve_message( $args ) {
      if ( stristr($args['subject'], 'Registration Approved') ){
      return null;
      }

      }

      Note that this is untested. It may not respond well to a null return value. You could also try returning false to see what happens.

      If you have changed the subject of the approval email either by hook or in the new user approve settings, you will need to adjust the search value in the conditional above where it says “Registration Approved” to include a string only present in your email’s subject line.

  16. Luke Cavanagh on September 11, 2017 at 2:56 pm

    Thank you for sharing.

  17. Fabrizio on August 21, 2017 at 3:49 pm

    Woocommerce credentials email is sent previous to approving… Is this meant this way?

  18. Kai on August 16, 2017 at 4:31 am

    Thanks for updating this! The old code stopped working with the last update. Much appreciated.

  19. Albert on July 3, 2017 at 8:16 am

    When you approve a user, the user receives two emails:
    -one from New User Approve WP Plugin
    -another from function ws_new_user_approve_send_approved_email

    How can we disable the default fron New User Approve plugin? or how we can apply woocommerce template to this one?

    Thanks

    • Jordan Schelew on July 12, 2017 at 8:52 pm

      Hmm good question. I’m not spotting anything in their docs indicating how to stop their email from being sent out… Might have to just stick with the built in one and not use my action hook to send another.

      • Pietro on August 28, 2017 at 2:03 pm

        Hi Jordan,

        we have solved a “two emails” problem?

        Thanks

        • Jordan Schelew on September 3, 2017 at 12:54 pm

          Pietro,

          I’m afraid I don’t use this solution on any live sites at the moment, so I don’t know! Last I looked into it, the simplest solution was to disable the code under “Notification Emails” above by removing it or commenting it out. This will ensure only the built in notifications are used and therefore two messages will not be sent.

          If you’d like to use the customized notifications, you’ll need to ask the “New User Approve” developer if they can include an option to disable their notifications, whether in the GUI settings or via action hook.

        • Jordan Schelew on September 18, 2017 at 11:42 am

          Hey Pietro,

          See above for both a hackish solution (edit the plugin code directly) and a possible untested solution using a WordPress filter on wp_mail().

          -Jordan

        • Alistair on March 21, 2018 at 4:17 pm

          Can you share what you did to stop the two emails please

          • Jordan Schelew on April 6, 2018 at 5:31 pm

            Alistair,

            Further up in these comments someone else brought up this issue with duplicate emails. Because there appears to be no way to suppress the built in New User Approve email (other than commenting out their code, which will get overwritten on update), you’ll have to simply comment out the custom email system that was part of this guide. Perhaps the New User Approve folks will add an option to suppress their email in the future. If you find a sustainable (through updates) way to do this, please do update here!

            Note: also above is some untested code that I wrote that *might* do the trick. But I’d rather someone familiar with PHP/WordPress code test and modify it accordingly as I have no idea how it will behave!



          • Araceli on April 17, 2018 at 5:26 pm

            I have edited the file new-user-approve\includes\messages.php
            I have commented this two functions. I am not a professional, but it seems to work, now I only receive one email.
            Hope it helps you too

            function nua_default_approve_user_message() {
            /*$message = __( ‘You have been approved to access {sitename}’, ‘new-user-approve’ ) . “\r\n\r\n”;
            $message .= “{username}\r\n\r\n”;
            $message .= “{login_url}\r\n\r\n”;
            $message .= __( ‘To set or reset your password, visit the following address:’, ‘new-user-approve’ ) . “\r\n\r\n”;
            $message .= “{reset_password_url}”;

            $message = apply_filters( ‘new_user_approve_approve_user_message_default’, $message );*/

            return;
            }

            /**
            * The default email message that will be sent to users as they are denied.
            *
            * @return string
            */
            function nua_default_deny_user_message() {
            /*$message = __( ‘You have been denied access to {sitename}.’, ‘new-user-approve’ );

            $message = apply_filters( ‘new_user_approve_deny_user_message_default’, $message );*/

            return;
            }



          • Jordan Schelew on July 26, 2018 at 11:02 pm

            Great! I see no reason why that wouldn’t do the trick, except if there are any updates to the plugin, that change will likely be overwritten and need to be made again.



          • Alexander O on July 26, 2018 at 9:53 pm

            Just add this before add_action('new_user_approve_approve_user'

            remove_action( 'new_user_approve_approve_user', array( pw_new_user_approve(), 'approve_user' ) );



Leave a Comment