Issue with foreach on duplicate meta_key’s

Im storing using add_user_meta custom values that get sent to the front page of the website. Here is the php code.

$user_query = new WP_User_Query( array(
          'fields' => 'ID'
      ) );
    $user_ids = $user_query->get_results();
    foreach( $user_object->_custom_link as $user_id ) {
        $user_object = get_userdata( $user_ids );
        echo '<li class="quick-link custom"><img src="http://compass/wp-content/uploads/2015/12/add-icon.png" /><h2><a href="'.$user_object->_custom_link.'">Custom Link</a></h2></li>';
    }

When everything generates, only one meta value is returned, but multiple values can be stored.enter image description here

My question is, right now my loops is checking ID only, im not entirely sure how to get it to check id, then check how many meta_keys of _custom_link there are.
enter image description here

This shows that only one meta_key is being returned. ALso if you have a better method that would be greatly appreciated.

2 Answers
2

Here is an example of getting the user IDs, looping through each, grabbing a meta_key as an array, adding new values to it and remove old values, saving the meta back, then grabbing it again to loop through each item in the array for output. Array is just an example of duplicate keys.

$user_query = new WP_User_Query( array( 'fields' => 'ID' ));
$user_ids = $user_query->get_results();

echo "<ul>";

foreach ( $user_ids as $user_id ) {

    // all meta for user
    $all_meta_for_user = array_map( function( $a ){ return $a[0]; }, get_user_meta( $user_id ) );

    echo "<pre>";
    print_r ( $all_meta_for_user ); // see all the values
    echo "</pre>";

    $key = '__TEST_KEY';
    $value_set = array();
    if( isset( $all_meta_for_user [ $key ] )) {
        $value_set = get_user_meta ( $user_id, $key, true );
        if( ! is_array( $value_set )) $value_set = array(); // make sure we're working with an array
    }

    // add to existing values
    $value_set[] = timer_stop(4);

    // remove old items
    if( count ($value_set) > 4 ) array_shift ($value_set);

    // set the meta
    update_user_meta($user_id, $key, $value_set );

    // LATEST VALUES
    $value_set = get_user_meta ( $user_id, $key, true );

    echo "<pre>";
    print_r ( $value_set ); // the value set currently in our meta
    echo "</pre>";

    foreach ( $value_set as $inx => $value ){
        echo "<li>{$user_id} - {$key} - {$inx} - {$value}</li>";
    }
    echo "</ul>";
}

echo "</ul>";

Leave a Comment