WordPress: Retrieve Parent Categories of a Post Using WP_Query
To get the categories of a post in WordPress using WP_Query, you can use the get_the_category() function. Here's an example:
$args = array(
'post_type' => 'post',
'posts_per_page' => -1 // Retrieve all posts
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$categories = get_the_category();
foreach ($categories as $category) {
if ($category->parent == 0) {
echo $category->name . '<br>'; // Output parent category name
}
}
}
wp_reset_postdata();
} else {
echo 'No posts found.';
}
In the above example, we are using WP_Query to retrieve all posts and then looping through each post using the_post() function. Within the loop, we use get_the_category() to retrieve the categories associated with the current post. We then iterate through the categories and check if the parent property is 0, which indicates a parent category. If it is, we output the category name.
Note that we also use wp_reset_postdata() after the loop to reset the post data to the main query. This is necessary if you are using this code within a template file to prevent any conflicts with other queries on the page.
原文地址: https://www.cveoy.top/t/topic/qCNM 著作权归作者所有。请勿转载和采集!