Blog

Sharing WordPress tips and tricks as I find them

Custom WordPress Queries

At the bottom of my individual posts in Thesis Tips, I used to have a list of all my Thesis Tips This just checks to see if the current post is tagged ‘thesis-tip’, and that it’s not on the homepage, and if it meets those criteria then it lists all Thesis Tips.

I use this technique for lots of things. It can show the most recent posts in the footer, list of certain posts on specific pages… any time you want to call WordPress and not mess with the main content (called “The Loop”).

The Query

For information on all the parameters you can use, see WP_Query in the Codex.

For my example, I’m going to get all the posts tagged ‘thesis-tip’ and put them in a list with just the title hyperlinked to the post itself.

Make sure you include the wp_reset_query(), which will (as the name implies) reset the query back to the default. If you don’t do this, WordPress will think the current page is whatever last item was in your new query, which will cause lots of issues (ex: comments from the wrong post showing up).

10 Comments

  1. Could this work with Sticky posts also?

  2. This worked great for a custom taxonomy I needed to pull onto a Featured Portfolio page. Thanks, Bill — hail to the king :)

  3. There is a spelling mistake in the line “if( $tips->hvae_posts() ):”

    “have”, instead of “hvae”!
    Just in case some will copy/paste the code. ;-)

  4. The code above is also missing an ENDIF; statement.

    • Bill Erickson says:

      Good catch. I’ve updated the code, so once my cache refreshes the change will be visible. Thanks!

  5. Hya,

    This is great, really helping me understand best practices for custom queries. Quick question and maybe kinda random: what the purpose of defining ‘posts_per_page’ => ‘-1′? I’ve tried to find answers on the forums, but can’t find an explanation. Why -1?

    thanks!

    • Bill Erickson says:

      -1 simply means “return all posts”. It indicates no limit on the number of posts per page. You could set an arbitrarily high number, like 9999, but -1 will always return all, so that’s why it’s the best practice.

Join the Conversation

If you'd like to include code in your post, please post it to http://gist.github.com and include a link.

%d bloggers like this: