0

I have created a custom usermeta field named "designation" and fetched all its meta value in loop but it shows duplicates and empty values. I have tried to resolve by using array_unique() function but it does not work. Please guide me how can remove duplicates and blank values.

 $args = array(
 'role' => 'subscriber',
 'meta_key' => 'user_designation'
        );

  // The Query  
  $design = array_unique($args);        
  $user_query = new WP_User_Query($design);

  // User Loop
  if ( !empty($user_query->results) ) {
    foreach ( $user_query->results as $user ) {
    ?>
    <option><?php echo get_user_meta($user->ID, 'user_designation', true); ?></option>
    <?php
    }
   }
   else {?>
        <option value="0">No Category Found</option>
  <?php } ?>

0

You can store the user meta in a variable and check if the variable is empty or not, like below-

$args = array(
    'role' => 'subscriber',
    'meta_key' => 'user_designation'
);

// The Query
$user_query = new WP_User_Query($args);
// User Loop
$u_meta_array = array();
if ( !empty($user_query->results) ) {
    foreach ( $user_query->results as $user ) {
        $u_meta = get_user_meta($user->ID, 'user_designation', true);
        if (!empty($u_meta)){
            $u_meta_array[] = $u_meta;
        }
    }
    $u_meta_array_unique = array_unique($u_meta_array);
    foreach ($u_meta_array_unique as $u ) {
        echo '<option>' . $u . '</option>';
    }
} else { ?>
    <option value="0">No Category Found</option>
<?php } ?>

Hope that thing is gonna work. Please let me know if it works or not.

|improve this answer|||||
  • Thank you so much it works for removing empty values but my another issue is still please let me know where i use array_unique() function to remove duplicates meta value – Yajuvendra Oct 25 '16 at 11:33
  • I don't think you need to use array_unique() any more here. It's already pretty fine I think. If this post helps you then please accept the answer. It would be very helpful. @Yajuvendra – CodeMascot Oct 25 '16 at 11:35
  • but there are shows duplicates value. so how can remove it – Yajuvendra Oct 25 '16 at 11:41
  • No. I don't think there is any duplicate value. It's actually I think same value for different users. Better you do a print_r() and attach those value to you question. So we can be sure that is duplicate or same value for different users. @Yajuvendra – CodeMascot Oct 25 '16 at 11:43
  • here is the my website [link] (pronetworker.com/people) please find out the select drop down option under Search People by Designation – Yajuvendra Oct 25 '16 at 11:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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