Skip to content

Instantly share code, notes, and snippets.

@keesiemeijer
Last active February 5, 2016 10:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keesiemeijer/36caff00c0ab02a01025 to your computer and use it in GitHub Desktop.
Save keesiemeijer/36caff00c0ab02a01025 to your computer and use it in GitHub Desktop.
WordPress — Query all posts in a taxonomy
<?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;
}
<?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