Change user meta value with shortcode

With shortcode, i want to create form to change the car’s name of user

function wp_change_namecar( $atts, $content = null  ) {
    if (is_user_logged_in()) {
        $user_id = get_current_user_id();
        $userval = //how to define that it is the value of the form?

          if (isset($_POST['validate_user'])) {
            if ($_POST['validate_user'] == $user_id) {
                if (update_user_meta( $user_id, 'user_name_car', '$userval' )) {
                    return "<div class='user_updated'>Updated!</div>";
                } else {
                    return "<div class='user_updated error'>Not Updated!</div>";
                }
            }
        }
        
        //Show the form
       return "<form method='post'>
       <label for='cars'>Choose a car:</label>
       <select id='cars' name='cars'>
         <option value='volvo'>Volvo</option>
         <option value='saab'>Saab</option>
         <option value='fiat'>Fiat</option>
         <option value='audi'>Audi</option>
       </select>
         <input type='submit' value='Change' />
       </form>";
        
    }
} 
add_shortcode('change_namecar','wp_change_namecar');

THX

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You made error, you made checks on the value which were null, i compile your code and made changes, here is the code it will help you.

function wp_change_namecar( $atts, $content = null  ) {
    if (is_user_logged_in()) {
        $user_id = get_current_user_id();
        $userval =$_POST['cars']; //how to define that it is the value of the form?

        if ($userval && $user_id) {
            if (update_user_meta( $user_id, 'user_name_car', $userval )) {
                return "<div class='user_updated'>Updated!</div>";
            } else {
                return "<div class='user_updated error'>Not Updated!</div>";
            }
        }    
        //Show the form
       return "<form method='post'>
       <label for='cars'>Choose a car:</label>
       <select id='cars' name='cars'>
         <option value='volvo'>Volvo</option>
         <option value='saab'>Saab</option>
         <option value='fiat'>Fiat</option>
         <option value='audi'>Audi</option>
       </select>
         <input type='submit' value='Change' />
       </form>";
        
    }
} 
add_shortcode('change_namecar','wp_change_namecar');


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x