Using WP_Query Your First Time: A Shortcode to Show Post Titles

Using WP_Query for the first time can be scary. If you’re an established programmer who is well acquainted with object-oriented programming, it’s pretty easy. But if you’re not you need to use WordPress’s looping concept, and an object, for the first time, and it’s a lot to take in. Don’t get overwhelmed. Copying and pasting the first few (dozen) times is how everyone learns. My hope is that the video gives you some understanding though:

Then I’ve got the word version:

How to Make a Custom Query in WordPress

  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. It’s the best resource ever for getting comfortable building these arguments up.
  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 the post. Technically you’re making the first post form the array the global post. (If that was all gibberish, don’t sweat it. I just said it for people who understand it already.) You do this with a $q->the_post() inside of your while loop.
  5. Then do what you’re going to do with posts from the loop. 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. This is good hygiene and you want to get in the habit so nothing breaks elsewhere because of your custom loop. Technically (again, if this means nothing to you, don’t worry) what we’re doing is resetting that global post to the one WordPress queried for on the page initially.

And finally, 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;
}

1 Response

Comments

Add a Comment

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