Skip to content

Instantly share code, notes, and snippets.

@curiouscrusher
Last active August 29, 2015 14:28
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 curiouscrusher/87a9b8261d9c70717683 to your computer and use it in GitHub Desktop.
Save curiouscrusher/87a9b8261d9c70717683 to your computer and use it in GitHub Desktop.
Wordpress query for multiple post types. Lets say you need to query 3 different post types, and load 1 post from each. Without diving headfirst into SQL and Unions, this is a simpler solution. While may not be the most efficient route, it does the job, and if you can spare less than a second of load/query time, it'll solve your problem.
<?php
// Add your post types to the array
$posttypes = array('post_type_1','post_type_3','post_type_3');
$randompost_typs = shuffle($posttypes);
$counter = count($posttypes);
// Add or remove additional post types as needed
for($i=0; $i<$counter;$i++) {
if($randompost_typs[$i]=='post_type_1') {
// I only wanted one post from each, but you can raise or lower the value if needed
$posts_per_page = 1;
} elseif($randompost_typs[$i]=='post_type_2') {
$post_per_page = 1;
} else {
$post_per_page = 1;
}
// Query arguements
$args = array(
'post_type' => $posttypes[$i],
// Orderby defaults to date, we're just setting it to ensure the latest posts load first
'orderby' => 'date
'posts_per_page' => $post_per_page
);
$query = new WP_Query( $args );
if($query->have_posts()) : while($query->have_posts()): $query->the_post();
// Add your own code for displaying posts below here
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment