Calling a method from functions.php on a click of a button

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

  1. Change the form tag 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 form now 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>
    
  2. Add this to the theme functions.php file:

    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:

    1. The Gdpr as in 'Gdpr' !== $_POST['accept'] is the same as in the <input name="accept" type="checkbox" value="Gdpr" required /> above.

    2. Be sure to replace the META_KEY with the actual meta key.

    3. I believe that the GDPR acceptance is aimed at logged-in users only, so that’s why I used is_user_logged_in() and get_current_user_id() in the above code/function.

UPDATE

wp_safe_redirect() didn’t work for the OP, so he used wp_redirect().

Leave a Comment