28
votes

I'm developing a wordpress plugin. I'm using two different custom post types, players and teams.

  • Players has relevant meta fields: First name, last name, and team.
  • Teams has relevant meta fields of team name.

While editing a specific team post, I'm trying to have an array of all the players that currently have that team's name posted to their meta field for team name. I'm not sure how to do this. Any help or articles would be really helpful. Thanks

2

2 Answers

25
votes

The important thing is that you are querying for posts using at least the three criteria of the post type, meta key, and meta value.

For example, let's assume your custom post type is just called "player" And, each 'player' post has a meta field attached called "player_team"

You could then query for those posts using something like this:

$teamname = ""; // the player's team that you're querying for

$myquery = new WP_Query( "post_type=player&meta_key=player_team&meta_value=$teamname&order=ASC" );
63
votes

Or using get_posts:

$args = array(
    'meta_key' => 'player_team',
    'meta_value' => $teamname,
    'post_type' => 'player',
    'post_status' => 'any',
    'posts_per_page' => -1
);
$posts = get_posts($args);

Another equivalent query using meta_query instead of meta_key and meta_value:

$args = array(
    'meta_query' => array(
        array(
            'key' => 'player_team',
            'value' => $teamname
        )
    ),
    'post_type' => 'player',
    'posts_per_page' => -1
);
$posts = get_posts($args);