Group Posts by Custom Taxonomy

Home » Snippets » Group Posts by Custom Taxonomy
0

Created with:

Visibility: 

public

Creator: Adriano

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php
/**
 * Plugin Name: WP Plugin
 * Description: Display posts from a custom post type and group them by a custom taxonomy.
 * Version: 1.0
 * Author: Your Name
 * License: GPL2
 */

function wpturbo_display_posts_by_custom_taxonomy() {
    $args = array(
        'post_type' => 'your_custom_post_type',
        'posts_per_page' => -1,
        'orderby' => 'title',
        'order' => 'ASC',
        'tax_query' => array(
            array(
                'taxonomy' => 'your_custom_taxonomy',
                'field' => 'term_id',
                'terms' => 'your_term_id',
            ),
        ),
    );

    $query = new WP_Query( $args );

    if ( $query->have_posts() ) {
        $grouped_posts = array(); // Initialize an array to store grouped posts
        
        while ( $query->have_posts() ) {
            $query->the_post();
            
            $terms = get_the_terms( get_the_ID(), 'your_custom_taxonomy' );
            
            if ( $terms && ! is_wp_error( $terms ) ) {
                foreach ( $terms as $term ) {
                    $grouped_posts[ $term->name ][] = get_the_title();
                }
            }
        }

        wp_reset_postdata();

        foreach ( $grouped_posts as $term_name => $post_titles ) {
            echo '<h2>' . esc_html( $term_name ) . '</h2>';
            echo '<ul>';
            
            foreach ( $post_titles as $post_title ) {
                echo '<li>' . esc_html( $post_title ) . '</li>';
            }
            
            echo '</ul>';
        }
    }
}

add_shortcode( 'custom_taxonomy_posts', 'wpturbo_display_posts_by_custom_taxonomy' );
				

Explanation:

Register an account to save your snippets or go Pro to get more features.