0

I have created a new custom meta for my wordpress users. These are just 2 radio buttons (either 'Yes' or 'No').

I have created a button on the front end and want it so that if the button is clicked, the value changes 'True'. By default it will be set to the value of 'No', and i wont have to worry about the button being clicked again as i am hiding the button once the value is set to 'True'.

Iv found a few ways where i can display a form with a submit button, but is this possible with just just one button, like below:

<button id="updateMyUserMeta" name="updateMyUserMeta">Update</button>

1 Answer 1

0

You can create a similar solution as the one with a form and submit button by adding an onclick event to your button:

<button id="updateMyUserMeta" name="updateMyUserMeta" onclick="window.location.href('http://example.com?my_custom_user_meta=true');">Update</button>

Then add this to the functions.php of your theme.

/**
 * Updates the 'my_custom_user_meta' field if the
 * user clicks the 'Update' button.
 */
function update_my_custom_user_meta() {

  if (empty($_GET['my_custom_user_meta']) {
    return;
  }

  $user_id = current_user_id();

  if (empty($user_id)) {
    return false;
  }

  update_user_meta( $user_id, 'my_custom_user_meta', true); 
}

add_filter('init', 'update_my_custom_user_meta');

Change http://example.com to the URL of your site and change my_custom_user_meta to the name of your user meta field.

To make this secure you should also look into adding nonce checks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.