Search code examples
phpwordpresswoocommerceregistration

Woocommerce: add a custom message on registration


I'm trying to add a message on the "my account" page with woocommerce when somebody registers for the first time from the same page - I don't want to do it if somebody registers while paying for an order.

I've been messing around for hours with filters and actions, and I can't manage to display my message just after the registration... The best thing I've managed to do with the function wc_add_notice is to display it but on every single part of "my account" page.

I don't want the user to end up on a custom page, just add some kind of success message.

Could someone help me with that? I'd like to do it myself, without paying for a plugin for such a simple thing.


Solution

  • You'd have quite a bit of work here. WooCommerce does not distinguish between a user registering during checkout versus a user registering via the my account page. So, you would need to track this yourself, possibly via a POST variable.

    add_action('woocommerce_register_form_end', 'add_hidden_field_to_register_form');
    
    function add_hidden_field_to_register_form() {
    
        //we only want to affect the my account page
        if( ! is_account_page() )
            return;
    
        //alternatively, try is_page(), or check to see if this is the register form
    
        //output a hidden input field
        echo '<input type="hidden" name="non_checkout_registration" value="true" />';
    
    }
    

    Now, you will need to tie into the registration function so you can access this variable, and save as needed.

    add_action( 'woocommerce_created_customer', 'check_for_non_checkout_registrations', 10, 3 );
    
    function check_for_non_checkout_registrations( $customer_id, $new_customer_data, $password_generated ) {
    
        //ensure our custom field exists
        if( ! isset( $_POST['non_checkout_registration'] ) || $_POST['non_checkout_registration'] != 'true' )
            return;
    
        //the field exists. Do something.
        //since I assume it will redirect to a new page, you need to save this somehow, via the database, cookie, etc.
    
        //set a cookie to note that this user registered without a checkout session
        setcookie( ... );
    
        //done
    }
    

    Finally, you can display the message on the page desired, if the cookie is set. You can unset the cookie as well, to ensure you do not show it again.

    This could be done via an action or filter, if a custom function, or a theme file.

    if( $_COOKIE['cookie_name'] ) {
        //display message
        //delete the cookie
    }
    

    There may be a simpler solution, but this would work...