Last active
December 18, 2015 07:29
-
-
Save hissy/5747126 to your computer and use it in GitHub Desktop.
[WordPress] Get posts by taxonomy of a post type.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// get post type | |
$post_type = get_post_type(); | |
//$post_type = get_query_var('post_type'); // in post type archive | |
// get taxonomy objects of the post type | |
$post_type_taxonomies = get_object_taxonomies( $post_type, 'objects' ); | |
if ( !empty($post_type_taxonomies) ) { | |
foreach( $post_type_taxonomies as $post_type_taxonomy ) { | |
// use only hierarchical taxonomy | |
if ( is_object($post_type_taxonomy) && $post_type_taxonomy->hierarchical ) { | |
// get terms by taxonomy name | |
$terms = get_terms( $post_type_taxonomy->name ); | |
if ( ! is_wp_error( $terms ) ) { | |
foreach ( $terms as $term ) { | |
// get posts by each term | |
$args = array( | |
'post_type' => $post_type, | |
'tax_query' => array( | |
array( | |
'taxonomy' => $term->taxonomy, | |
'field' => 'slug', | |
'terms' => $term->slug | |
) | |
) | |
); | |
$myposts = get_posts( $args ); | |
echo '<h3>' . $term->name . '</h3>'; | |
echo '<ul>'; | |
foreach( $myposts as $post ) { | |
setup_postdata($post); | |
echo '<li>' . get_the_title() . '</li>'; | |
} | |
echo '</ul>'; | |
wp_reset_postdata(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment