Revision 474 is a pre-publication revision. (Viewing current revision instead.)

WordPress: combine two queries into one loop

[php] <?php $term = get_term_by( 'slug', get_query_var( 'tag' ), "post_tag" ); $tagslug = $term->slug; $post_types = get_post_types('','names'); ?> <?php //first query $blogposts = get_posts(array( 'tag' => $tagslug, //first taxonomy 'post_type' => $post_types, 'post_status' => 'publish', )); //second query $authorposts = get_posts(array( 'bookauthor' => $tagslug, //second taxonomy 'post_type' => $post_types, 'post_status' => 'publish', )); $mergedposts = array_merge( $blogposts, $authorposts ); //combine queries $postids = array(); foreach( $mergedposts as $item ) { $postids[]=$item->ID; //create a new query only of the post ids } $uniqueposts = array_unique($postids); //remove duplicate post ids $posts = get_posts(array( 'post__in' => $uniqueposts, //new query of only the unique post ids on the merged queries from above 'post_type' => $post_types, 'post_status' => 'publish', )); foreach( $posts as $post ) : setup_postdata($post); ?> [/php]

Revisions

Revision Differences

July 2, 2013 @ 12:11:19Current Revision
Content
 Added: [php]
 Added: &lt;?php
 Added: $term = get_term_by( 'slug', get_query_var( 'tag' ), &quot;post_tag&quot; );
 Added: $tagslug = $term-&gt;slug;
 Added: $post_types = get_post_types( '','names');
 Added: ?&gt;
 Added: &lt;?php
 Added: //first query
 Added: $blogposts = get_posts(array(
 Added: 'tag' =&gt; $tagslug, //first taxonomy
 Added: 'post_type' =&gt; $post_types,
 Added: 'post_status' =&gt; 'publish',
 Added: ));
 Added: //second query
 Added: $authorposts = get_posts(array(
 Added: 'bookauthor' =&gt; $tagslug, //second taxonomy
 Added: 'post_type' =&gt; $post_types,
 Added: 'post_status' =&gt; 'publish',
 Added: ));
 Added: $mergedposts = array_merge( $blogposts, $authorposts ); //combine queries
 Added: $postids = array();
 Added: foreach( $mergedposts as $item ) {
 Added: $postids[]=$item-&gt;ID; //create a new query only of the post ids
Deleted: Added: }
 Added: $uniqueposts = array_unique($postids); //remove duplicate post ids
 Added: $posts = get_posts(array(
 Added: 'post__in' =&gt; $uniqueposts, //new query of only the unique post ids on the merged queries from above
 Added: 'post_type' =&gt; $post_types,
 Added: 'post_status' =&gt; 'publish',
 Added: ));
 Added: foreach( $posts as $post ) :
 Added: setup_postdata($post);
 Added: ?&gt;
 Added: [/php]

Note: Spaces may be added to comparison text to allow better line wrapping.

Tags: , ,

No comments yet.

Leave a Reply