Running Queries From Functions.php – Update, Let's Keep This Thing in Check!

Back in August, I ran a little article about running queries from functions.php. We did a little pre_get_posts work, and a bit of a conditional stuff. Well, I learned a bit more since then, and you need one more essential piece of information! Let me key you in on that!

While the solution I gave for you works nicely, I forgot to target it… we let it run wild! If you run that sort of query, what ends up happening is the query stomps all over everything! I noticed that when I ran my query, my widgets on that particular page ran in reverse order! Makes sense, the query I was running was intended to revers the order of my posts!

Let’s get that in check, how do we run a query on a particular page, without messing up menus, widgets, or anything else? Well, since what we are probably focusing on here is our main query, the content itself, we have is_main_query at our disposal! With that we can tell WordPress to only act on the main content brought in by the query, not any of the widgets, menus, etc.

So rather than explain it myself, you can check out this thread on the WordPress forums to see the background info, or jump straight to this post from Bill Erickson on his site. He does a better job explaining it than I probably would… but it’s as simple as adding is_main_query in addition to your existing conditional.

Leave a Reply