You could use AJAX if you don’t want to reload the current page — i.e. upon clicking the “Accept” button, make an AJAX request to update the user metadata, all without leaving the current page.
However, the solution I’m proposing is not using AJAX; instead, we simply submit the form (set its action attribute value) to the homepage and then we use the template_redirect hook to update the metadata (and redirect back to the previous or referring page).
The Steps
-
Change the
formtag to:<form method="post" action="<?php echo esc_url( home_url() ); ?>">and add this nonce field:
<?php wp_nonce_field( 'accept-gdpr', 'accept_gdpr_nonce' ); ?>so your
formnow looks like:<form method="post" action="<?php echo esc_url( home_url() ); ?>"> <input name="accept" type="checkbox" value="Gdpr" required /> I accept the GDPR <input type="submit" id="accept-button" value="Accept" /> <?php wp_nonce_field( 'accept-gdpr', 'accept_gdpr_nonce' ); ?> </form> -
Add this to the theme
functions.phpfile:function accept_gdpr() { // Check if the user is authenticated. if ( ! is_user_logged_in() ) { return; } // Check if we have all necessary data. if ( empty( $_POST['accept_gdpr_nonce'] ) || empty( $_POST['accept'] ) || 'Gdpr' !== $_POST['accept'] ) { return; } // Verify the nonce. if ( ! wp_verify_nonce( $_POST['accept_gdpr_nonce'], 'accept-gdpr' ) ) { return; } // Update the meta. update_user_meta( get_current_user_id(), 'META_KEY', '1' ); // Redirect back to the previous page. wp_safe_redirect( wp_get_referer() ); exit; } add_action( 'template_redirect', 'accept_gdpr' );Notes:
-
The
Gdpras in'Gdpr' !== $_POST['accept']is the same as in the<input name="accept" type="checkbox" value="Gdpr" required />above. -
Be sure to replace the
META_KEYwith the actual meta key. -
I believe that the GDPR acceptance is aimed at logged-in users only, so that’s why I used
is_user_logged_in()andget_current_user_id()in the above code/function.
-
UPDATE
wp_safe_redirect() didn’t work for the OP, so he used wp_redirect().