📅  最后修改于: 2023-12-03 14:48:34.600000             🧑  作者: Mango
In WordPress, WP_Query is a powerful class that allows developers to retrieve posts based on various parameters. One of these parameters is the ability to order the query results by taxonomy terms.
Here's an example of how you can use WP_Query to order posts by taxonomy in PHP:
$args = array(
'post_type' => 'post', // Replace 'post' with your desired post type
'orderby' => 'term_order', // Order by term order
'tax_query' => array(
array(
'taxonomy' => 'category', // Replace 'category' with your desired taxonomy
'field' => 'term_id',
'terms' => array(1, 2, 3), // Replace with the term IDs you want to include
),
),
);
$query = new WP_Query($args);
In the above example, we set the orderby
parameter to term_order
to order the posts by the term order within the specified taxonomy.
We also specify the tax_query
parameter to filter the query results based on the taxonomy terms. You need to replace 'category' with the desired taxonomy and provide the term IDs you want to include.
Once you have the WP_Query object, you can loop through the posts using a standard WordPress loop:
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
// Display post content here
}
} else {
// No posts found
}
wp_reset_postdata(); // Reset the global post object
You may need to customize the code further based on your specific requirements, but this gives you a starting point to order query results by taxonomy in WordPress using WP_Query.
Remember to replace the post type, taxonomy, and term IDs with your own values, and modify the post display code to suit your needs.
I hope this helps you understand how to use WP_Query to order posts by taxonomy in WordPress!