plugins – Shortcode to update user meta

Question

Basically, you can’t show the button and update the meta at the same moment. This has to be done in two separate requests as follows:

  1. Show the button whereever you want. It needs to be a form that submits to the same page (or an ajax call to another URL, but let’s keep it simple for now).
  2. Read the value posted from the form.

Here is a simple implementation to make this work, but it can be way improved.

function wpses_385303_change_validate() {
    if (is_user_logged_in()) {
        $user_id = get_current_user_id();
        
        //If the form was posted (ie. the button was clicked) in a previous request
        if (isset($_POST['validate_user'])) {
            if ($_POST['validate_user'] == $user_id) {//A little bit of security
                if (update_user_meta( $user_id, 'User_meta_change', 'validated' )) {
                    return "<div class="user_updated">Updated!</div>";
                } else {
                    return "<div class="user_updated error">Not Updated!</div>";
                }
            }
        }
        
        //Show the form
        return "<form method='post'>
            <input type="hidden" name="validate_user" value="$user_id" />
            <input type="submit" value="Validate" />
            </form>";
        
    }
} 
add_shortcode('change_validate','wpses_385303_change_validate');

0
Olivier 4 weeks 2021-03-18T08:46:39-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse