In this video and text Quick Guide, we present a basic use of WP_Query
inside a WordPress shortcode, to show the post titles of the five most recently published posts. We’ve designed this Quick Guide to be a simple intro to using WP_Query
in general, as well as to using WP_Query
to display post titles and other post data inside a shortcode specifically.
Here’s a video guide to this use of WP_Query
in a shortcode:
And here’s a text guide to the information in the video:
How to Create a Custom WP_Query
in a WordPress Shortcode
The steps are as follows:
- Write a line assigning the value from
new WP_Query()
to a named variable. In the video I used$q
. - Add the argument array to the
WP_Query
to match your needs. In the video we usedpost_type
andposts_per_page
. You should always refer to the Codex page on the topic if you have questions. - After this, you’ll typically use the WordPress “loop” process to iterate through the elements you’ve queried. In our case, we used
while($q->have_posts())
to start that going. - Then you need to “load” up each post inside your
while
loop, with$q->the_post()
. - Then do whatever it is you’d like to do with the posts you’re looping through. In the video, what we did was simply to stick the post title from the loop onto an existing
$buffer
variable, and then add an HTML line break. That code was$buffer = $buffer.get_the_title().'<br>';
. - After you end the
while
loop, it’s best practice to put a call towp_reset_postdata()
in there. You want to get in the habit of doing this so that nothing breaks elsewhere because of your custom loop.
Working Code: A Post Titles Shortcode Using WP_Query
Here’s the full code in one big block:
add_shortcode( 'qg_shortcode', 'qg_shortcode' );
function qg_shortcode() {
$buffer = '<h3>Post Titles</h3>';
$q = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => 5
));
while ($q->have_posts()) {
$q->the_post();
$buffer = $buffer.get_the_title().'<br>';
}
wp_reset_postdata();
return $buffer;
}
Further Reading on WP_Query
, WordPress Custom Queries, and Shortcodes
If you have questions about any part of the above, or if you’d like to learn more about the wonderful worlds of WordPress shortcodes, WP_Query
, and WordPress template tags such as get_the_title()
, then please check out these additional resources:
Thanks for reading, and have fun writing your custom queries!