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:

WP_Query: Understand it, Love it!

Making Your First WordPress Shortcode

WordPress Template Tags: How They Show Post Content & More

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


5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Martin
September 15, 2020 12:41 pm

Hello I tried to lift and mix-up your advice to convert my function into a shortcode, but failed – I was wondering if you could help me workout how to top and tail this to make it a shortcode. It works, searches the post I’m in and returns the associated posts in a list. But I have to add it to the templates using but would like to add via a shortcodem – thank you in advance

function example_cats_related_post2() {

$post_id = get_the_ID();
$cat_ids = array();
$categories = get_the_category( $post_id );

if(!empty($categories) && is_wp_error($categories)):
foreach ($categories as $category):
array_push($cat_ids, $category->term_id);
endforeach;
endif;

$current_post_type2 = get_post_type($post_id);
$query_args = array(

‘category__in’ => $cat_ids,
‘post_type’ => $current_post_type2,
‘post__not_in’ => array(get_the_ID()), // Exclude current post
‘posts_per_page’ => ‘2’, // How many items to display
‘no_found_rows’ => true, // We don’t ned pagination so this speeds up the query
‘orderby’ => ‘rand’ // Random order
);

$related_cats_post2 = new WP_Query( $query_args );

if($related_cats_post2->have_posts()):
while($related_cats_post2->have_posts()): $related_cats_post2->the_post(); ?>

<a href="”>
<?php the_title( '’, ” ); ?>

<?php endwhile;

// Restore original Post Data
wp_reset_postdata();
endif;
}

Pascal
June 3, 2020 7:19 am

May be ?

add_shortcode( ‘px_post_title’, ‘px_post_title’ );
function px_post_title() {
$post_title = get_the_title($post = 514);
return $post_title;
}

Pascal
June 3, 2020 3:56 am

Hello and thank you for this code. iā€™m searching for a shortcode like [post_title post_id=3] to display in a page the title of a the post number 3. Is it possible ? Thanks

Andre
October 9, 2019 9:12 am

Thank you! Your code helped me a lot!

Cheenachatti
April 5, 2018 8:32 am

Thanks for the code. Used it successfully in my website to list tagged posts as short code.