Skip to content

Instantly share code, notes, and snippets.

@knolaust
Last active January 30, 2024 15:08
Show Gist options
  • Save knolaust/67e52685b939bfe6c3620fbfabc60b39 to your computer and use it in GitHub Desktop.
Save knolaust/67e52685b939bfe6c3620fbfabc60b39 to your computer and use it in GitHub Desktop.
Get posts from Custom Post Type grouped by Custom Taxonomy
<?php
/**
* Get posts from Custom Post Type grouped by Custom Taxonomy
*
* Gist Keywords: wordpress, custom post types, cpt, taxonomy
* Author: Knol Aust
* Version: 1.0.0
* Description: This code retrieves posts from a custom post type and groups them by a custom taxonomy.
*/
// Setup variable array for terms in a custom taxonomy
$tax_group_terms = get_terms( array(
'taxonomy' => '##taxonomy-name##', // Replace with your custom taxonomy name (e.g., members)
// Additional sorting for array
'order' => 'ASC',
'orderby' => 'menu_order',
) );
// Loop through terms in taxonomy
foreach ( $tax_group_terms as $tax_group_term ):
// Setup arguments to query CPTs by terms
$args = array(
'post_type' => '##post-type-name##', // Replace with your custom post type name (e.g., member-types)
// Additional parameters for sorting and output
'order' => 'ASC',
'orderby' => 'menu_order',
'posts_per_page' => 1000,
// Terms argument for the current term in the foreach loop
'tax_query' => array(
array(
'taxonomy' => '##taxonomy-name##', // Replace with your custom taxonomy name (e.g., members)
'field' => 'slug',
'terms' => array( $tax_group_term->slug ),
'operator' => 'IN'
)
)
);
// Query Custom Post Type (e.g., members) by the current taxonomy type (e.g., premium or standard)
$cpt_group_query = new WP_Query($args);
// If there are members in this type, output the section
if ( $cpt_group_query->have_posts() ) :
// Output the taxonomy term name
echo $cpt_group_query->name;
// Loop through custom posts matching the term and output
while ( $cpt_group_query->have_posts() ) : $cpt_group_query->the_post();
// Output details from post
the_title();
the_content();
endwhile;
// Reset query
wp_reset_postdata();
endif;
endforeach;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment