• Hey all,
    I’ve seen heaps of custom queries up that solve individual cases where people want to search a particular post type and filter it by a custom taxonomy and term, but nothing that was a reusable function. So I wrote one. This is far from perfect, but it suits my purposes until this sort of query is built into WP.

    I’m merely putting this code out there to save someone else from doing it later. If you find a bug or have a suggestion please add it to the code and post it up here for all to use.

    Just dump this code in your functions.php file and call it in place of something like get_posts().

    /*-------------------------------------------------------------------
    Get Posts by a Taxonomy Terms
    by Benji Greig [email protected]
    -------------------------------------------------------------------
    This function allows for a query to be made similar to get_posts but
    allows for filtering by 'taxonomy_name' and multiple taxonomy terms.
    
    You can filter the query by comma delimited lists of:
    		- 'taxonomy_terms'
    		- 'post_types'
    
    Additionally you can filter the query by 'post_status' and define
    the 'orderby' from any of the posts fields and set either ascending
    or decending. It's not perfect, but it's coming in real handy for
    making special queries.
    -------------------------------------------------------------------*/
    
    function get_posts_by_taxonomy($args) {
    	global $wpdb;
    //
    	if ( is_array($args) )
    	  $options = &$args;
    	else
    	  parse_str($args, $options);
    //
    	$defaults = array(
    		'post_type' => null,
    		'post_status' => 'publish',
    		'taxonomy_name' => null,
    		'taxonomy_term' => null,
    		'orderby' => 'post_date',
    		'order' => 'DESC',
    		'numberposts' => '10'
    	);
    	$options = array_merge($defaults, $options);
    	extract($options);
    //
    	//Format the post_type list so that it works in the query
    	$post_type = "('".str_replace(",","', '",$options['post_type'])."')";
    //
    	//Get the term IDs from the Term Names
    	$terms = split('[,]', $options['taxonomy_term']);
    	$term_ids = $options['taxonomy_term'];
    	foreach($terms as $term){
    		$t_data = term_exists($term, 'show-in');
    		$term_ids = str_replace($term,"'".$t_data['term_id']."'",$term_ids);
    	}
    	$term_ids = "(".$term_ids.")";
    //
    	//Build the query
    	$query = "SELECT $wpdb->posts.* FROM $wpdb->posts
    	INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
    	INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
    	WHERE 1=1
    	";
    	if($options['taxonomy_name'] != null){$query .="AND $wpdb->term_taxonomy.taxonomy = '".$options['taxonomy_name']."'
    	";
    	if($options['taxonomy_term'] != null){$query .="AND $wpdb->term_taxonomy.term_id IN $term_ids
    	";}
    	}
    	if($options['post_type'] != null){$query .="AND $wpdb->posts.post_type IN $post_type
    	";}
    	$query .="AND $wpdb->posts.post_status = '".$options['post_status']."'
    	";
    	$query .="GROUP BY $wpdb->posts.ID
    	";
    	$query .="ORDER BY $wpdb->posts.".$options['orderby']." ".$options['order'];
    
    	$my_posts = $wpdb->get_results($query);
    	return($my_posts);
    
    }

    Here is an example usage of it:

    $args = array(
    	'post_status' => 'publish',
    	'taxonomy_name' => 'show-in',
    	'taxonomy_term' => 'al-pacino, robert-de-niro'
    );
    $custom_posts = get_posts_by_taxonomy($args);

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter benjibuls

    (@benjibuls)

    Thread Starter benjibuls

    (@benjibuls)

    Oh forgot to put this in just in case. An example of using this with a loop:

    $args = array(
    	'post_status' => 'publish',
    	'taxonomy_name' => 'show-in',
    	'taxonomy_term' => 'al-pacino, robert-de-niro'
    );
    $custom_posts = get_posts_by_taxonomy($args);
    
    <?php if ($custom_posts): ?>
    <?php foreach ($custom_posts as $post): ?>
    <?php setup_postdata($post); ?>
    
    	<?php the_title(); ?><br />
    	<?php the_content(); ?>
    
    <?php endforeach; ?>
    <?php else : ?>
        <h2 class="center">Not Found</h2>
        <p class="center">Sorry, but you are looking for something that isn't here.</p>
        <?php include (TEMPLATEPATH . "/searchform.php"); ?>
    <?php endif; ?>

    Heya.

    You left your taxonomy hard coded. ??

    $t_data = term_exists($term, 'show-in');

    Maybe..?

    $t_data = term_exists($term, $options['taxonomy_name']);

    ~loothi

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Query Posts by Taxonomy’ is closed to new replies.