Simple WP_Query Example: Using a Shortcode to Display Post Titles

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:

  1. Write a line assigning the value from new WP_Query() to a named variable. In the video I used $q.
  2. Add the argument array to the WP_Query to match your needs. In the video we used post_type and posts_per_page. You should always refer to the Codex page on the topic if you have questions.
  3. 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.
  4. Then you need to “load” up each post inside your while loop, with $q->the_post().
  5. 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>';.
  6. After you end the while loop, it’s best practice to put a call to wp_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:

Working with WP_Query

Making Your First WordPress Shortcode

WordPress Template Tags: How They Show Post Content & More

Thanks for reading, and have fun writing your custom queries!


2 Responses

Comments

Add a Comment

Your email address will not be published. Required fields are marked *