1

I just wanted to know whether it is possible to set for all users show-admin_bar_front meta data to true. I've tried this to put those lines in functions but with no results :

// Create the WP_User_Query object
$wp_user_query = new WP_User_Query(array('role' => 'Subscriber'));

// Get the results
$users = $wp_user_query->get_results();

// Check for results
if (!empty($users)) {
    // loop trough each author
    foreach ($users as $user) {
        // add points meta all the user's data
        update_user_meta(5, 'show_admin_bar_front', 'true');
    }
}

1 Answer 1

2

You can use update_user_option() function (see codex)

Your loop looks fine to me, so probably this would work:

// Create the WP_User_Query object
$wp_user_query = new WP_User_Query(array('role' => 'Subscriber'));

// Get the results
$users = $wp_user_query->get_results();

// Check for results 
if (!empty($users)) {

    // loop trough each author
    foreach ($users as $user)
    {
        // update option
        update_user_option( $user->ID, 'show_admin_bar_front', 'true');
    }
}

Things to pay attention to:

  1. You're looping through all queried users, so in update_user_option the first parameter needs to be the id retrieved from current user object (not the hardcoded ID)

  2. The third parameter in update_user_option should be of a string type apparently, so "true", not true

5
  • Hi thanks a lot for your answer. I put it in my functions.php with no result.
    – CRavon
    Commented Mar 30, 2018 at 11:22
  • Hello again, sorry for my mistake - apparently you need to set the option to 'true' - it's a string after all, not boolean. I've just tested this and it works fine. I've updated the code in my answer. Commented Apr 1, 2018 at 21:32
  • Yes thanks a lot. But it's kind a strange because It doesn't work on the first 300 users... Could it be that they never activated so the user's meta does not even get updated ?
    – CRavon
    Commented Apr 3, 2018 at 11:05
  • No, i don't think so - i'd bet that it was caused by the server timeout if your site is big. By default WP_User_Query will try to loop through all of your users: github.com/WordPress/WordPress/blob/master/wp-includes/…. You might wanna try to limit the number of users retrieved at once using the number parameter and move to next batch with offset parameter. In general performing operations on big sets of data are best done with WP CLI, not inside your functions.php: wp-cli.org Commented Apr 3, 2018 at 11:38
  • Thanks a a lot. It was definitely that. I 've used "include" and "exclude" parameters from the WP_User_Query to update users bt batch and it works like a charm. Thx
    – CRavon
    Commented Apr 3, 2018 at 12:45

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.