Blog / WordPress/ How to Loop Through All Taxonomy Terms and Posts for a Custom Post Type in WordPress

How to Loop Through All Taxonomy Terms and Posts for a Custom Post Type in WordPress

WordPress获取自定义文章类型所有分类法文章循环

In previous articles, we have covered WordPress Custom Post Types and provided a practical example of building a website directory using them. This tutorial will explain how to retrieve all taxonomies and loop through posts for a custom post type.

Implementation Code

Here is the functional code to achieve this:

<?php
// Get all top-level terms for a custom taxonomy
$args = array(
    'taxonomy'   => 'sitecat', // Your custom taxonomy name
    'hide_empty' => false,     // Show empty terms
    'parent'     => 0,         // Get only top-level terms
);
$categories = get_categories($args);

// Loop through each category
foreach ($categories as $category) {
    $cat_id = $category->term_id;
    ?>
    <!-- Output the category title -->
    <h2><?php echo esc_html($category->name); ?></h2>
    
    <?php
    // Query posts belonging to this category
    $custom_posts = new WP_Query(array(
        'post_type'      => 'site', // Your custom post type name
        'posts_per_page' => 8,      // Number of posts per page
        'tax_query'      => array(
            array(
                'taxonomy' => 'sitecat',
                'field'    => 'term_id',
                'terms'    => $cat_id,
            ),
        ),
    ));
    
    // Start the post loop
    if ($custom_posts->have_posts()) :
        while ($custom_posts->have_posts()) : $custom_posts->the_post();
            ?>
            <!-- Loop template -->
            <h3><?php the_title(); ?></h3>
            <?php the_excerpt(); ?>
            <?php
        endwhile;
        wp_reset_postdata(); // Reset post data
    endif;
}
?>

Code Explanation

The code consists of two main parts:

  1. Retrieve Taxonomies: Uses get_categories() to fetch top-level terms (parent ID 0) for the specified custom taxonomy.
  2. Nested Post Loop: For each term, creates a WP_Query instance to query posts belonging to that term, then uses the standard have_posts() and the_post() loop to output content.

Important Notes

  • Replace sitecat and site with your actual custom taxonomy and post type names.
  • Always call wp_reset_postdata() after a custom query to restore the main query and avoid conflicts.
  • The example uses the_title() and the_excerpt() for output; you can replace these with other template tags as needed.

Usage

This code retrieves all terms and their associated posts for a custom post type. To use it, create a custom taxonomy template for your post type. Ensure any shortcodes or embedded links in your template are functional.

Post a Comment

Your email will not be published. Required fields are marked with *.