dremme
dremme

Reputation: 769

Wordpress - get post based on meta field content

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

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

Upvotes: 33

Views: 71469

Answers (2)

jnpdx
jnpdx

Reputation: 52347

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( array(
    'post_type' => 'player',
    'meta_key' => 'player_team',
    'meta_value' => $teamname,
    'order' => 'ASC'
));

Upvotes: 25

colllin
colllin

Reputation: 9779

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);

Upvotes: 70

Related Questions