Skip to content

Instantly share code, notes, and snippets.

@amielucha
Last active November 2, 2018 16:55
Show Gist options
  • Save amielucha/96f6e2bb65c6d4d5574688a408516cfd to your computer and use it in GitHub Desktop.
Save amielucha/96f6e2bb65c6d4d5574688a408516cfd to your computer and use it in GitHub Desktop.
WP_Query() usage examples - WordPress custom post types (keywords: query, loop)
<?php
/*
* Display 4 items from Member post type.
* Posts are organized by menu order.
* Use https://wordpress.org/plugins/simple-page-ordering/ or similar to easily sort items.
*/
$the_query = new WP_Query( array(
'post_type' => 'member',
'posts_per_page' => 4,
'orderby' => 'menu_order',
'order' => 'ASC'
));
/*
* Display 3 recent items from Project CPT and of 'our-selected-category' Project Type taxonomy
*/
$the_query = new WP_Query( array(
'post_type' => 'project',
'tax_query' => array(
array(
'taxonomy' => 'project-type',
'field' => 'slug',
'terms' => 'our-selected-category',
),
),
'posts_per_page' => 3,
));
/*
* Display 4 recent items from Project CPT matching a custom field value (in this case a checkbox with value = 1)
*/
$the_query = new WP_Query( array(
'post_type' => 'project',
'meta_key' => 'wpcf-feat',
'meta_value' => 1,
'posts_per_page' => 4,
));
/* ------------------------------------------------
* Use in the template file.
*/
if ( $the_query->have_posts() ) {
echo '<div class="wrapper members-wrapper">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$res= '<a href="' . get_post_permalink() . '" class="members-item">';
$res.= '<div class="members-inner">';
if (has_post_thumbnail())
$res.= get_the_post_thumbnail();
$res.= '<div class="members-text"><h5 class="members-name">' . get_the_title() . '</h5>';
$res.= '</div></div></a>';
echo $res;
}
echo '</div>';
wp_reset_postdata();
} else {
echo "<h2>No members? That's strange.</h2>";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment