Last active
February 5, 2016 10:17
-
-
Save keesiemeijer/36caff00c0ab02a01025 to your computer and use it in GitHub Desktop.
WordPress — Query all posts in a taxonomy
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 | |
// Add a new public query variable: taxonomy_archive | |
add_filter ( 'query_vars', 'add_taxonomy_query_var' ); | |
function add_taxonomy_query_var( $query_vars ) { | |
$query_vars['taxonomy_archive'] = ''; | |
return $query_vars; | |
} | |
add_action( 'posts_clauses', 'taxonomy_archive_clauses', 10, 2 ); | |
function taxonomy_archive_clauses( $pieces, $query ) { | |
global $wpdb; | |
$archive_query = $query->get( 'taxonomy_archive' ); | |
// Check if it's a query for a taxonomy archive | |
if ( !empty( $archive_query ) ) { | |
// Query for the taxonomy provided in the taxonomy_archive query variable | |
$pieces['join'] .= " INNER JOIN {$wpdb->term_relationships} tr_tarchive ON ($wpdb->posts.ID = tr_tarchive.object_id)"; | |
$pieces['join'] .= " INNER JOIN {$wpdb->term_taxonomy} tt_tarchive ON (tr_tarchive.term_taxonomy_id = tt_tarchive.term_taxonomy_id)"; | |
$pieces['where'] .= $wpdb->prepare( " AND tt_tarchive.taxonomy = %s", $archive_query ); | |
} | |
return $pieces; | |
} |
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 | |
// Query for all posts that have terms from the movie custom taxonomy | |
$args = array( | |
'post_type' => array( 'post' ), | |
'taxonomy_archive' => 'movie', | |
); | |
// the query | |
$the_query = new WP_Query( $args ); ?> | |
<?php if ( $the_query->have_posts() ) : ?> | |
<!-- the loop --> | |
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> | |
<!-- Loop stuff here --> | |
<?php endwhile; ?> | |
<!-- end of the loop --> | |
<?php wp_reset_postdata(); ?> | |
<?php else : ?> | |
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> | |
<?php endif; ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment