How to select posts from taxonomy in wordpress?

by elise_daugherty , in category: PHP CMS , 9 months ago

How to select posts from taxonomy in wordpress?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lew , 9 months ago

@elise_daugherty 

To select posts from a specific taxonomy in WordPress, you can use the WP_Query class to customize your query. Here's an example of how you can select posts from a specific taxonomy:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$args = array(
    'post_type' => 'post', // Change 'post' to the post type you want to query
    'tax_query' => array(
        array(
            'taxonomy' => 'your_taxonomy', // Replace 'your_taxonomy' with the slug of the taxonomy you want to query
            'field' => 'id',
            'terms' => array( 1, 2, 3 ), // Replace the array with the term IDs you want to include
        )
    ),
);

$query = new WP_Query( $args );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // Display your post content here
    }
} else {
    // No posts found
}

wp_reset_postdata(); // Reset post data


In this code snippet:

  • Replace 'post' with your desired post type (e.g., 'page', 'custom_post_type').
  • Replace 'your_taxonomy' with the slug of the taxonomy you want to query.
  • Update the terms array with the term IDs you want to include in the query.


You can place this code in your template file (e.g. taxonomy-your_taxonomy.php) to show posts from a specific taxonomy in WordPress.