简体   繁体   中英

PHP, Wordpress Query, Combine Matched Results in 1

I am running a query in Wordpress to get a list of speakers from a custom post type. I only need one instance of each speaker returned even though a speaker may show up multiple times as meta for the custom post types.

So for example, if I query and get a list back like this: Bob, Bob, Bob, John, Sally, Bob, Bob, John, Bob

I would want it to be: Bob, John, Sally

I'm not sure how to group all the matched results with PHP.

Here is my query:

global $post;
  $args = array (
    'post_type' = 'event',
    'posts_per_page' = -1,
    'post_status' => 'publish',
    'fields' => 'ids',
    'meta_query' => array (
      'relation' => 'AND'
      array (
        'key' => 'pt_eventSpeakerType',
        'value' => 'Lead Speaker',
        'compare' => '=',
      ),
    ),
  );
$posts = get_posts($args);
if($posts) :
  foreach($posts as $post):setup_postdata($post);
    echo get_post_meta($post->ID, 'pt_eventSpeaker' true).'<br>';
  endforeach;
endif;
wp_reset_postdata();

Any help is appreciated!

from what you described, I assume that you are not creating SQL query correctly. Method get_posts($args); is probably not returning distinct results, that may be the problem with your duplicated values. I hope it helps.

I figured it out. This may not be the best way, but it works and doesn't require any alteration of the query: I found a PHP array function called array_unique

First I have to return all the speaker names in a foreach loop and then convert that to an array of its own. It gets rid of all the other objects returned by WP_Query .

Then use the array_unique function to sort those into an array of single entries for each speaker name.

Finally, using another foreach to loop through those names and output them.

global $post;
  $args = array (
    'post_type' = 'event',
    'posts_per_page' = -1,
    'post_status' => 'publish',
    'fields' => 'ids',
    'meta_query' => array (
      'relation' => 'AND'
      array (
        'key' => 'pt_eventSpeakerType',
        'value' => 'Lead Speaker',
        'compare' => '=',
      ),
    ),
  );
$posts = get_posts($args);
if($posts) :
  foreach($posts as $post):setup_postdata($post);
    $speakerName = get_post_meta($post->ID, 'pt_eventSpeaker', true);
    $speakers[]= $speakerName;
  endforeach;
  $names = array_unique($speakers);
  foreach($names as $name) :
    echo $name.'<br>';
  endforeach;
else :
  echo 'No Posts Found.';
endif;
wp_reset_postdata();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM