Solution for query_posts() Breaking Things & Causing Havoc

According to my experience and WordPress support forum entries like http://wordpress.org/support/topic/185209 , the very powerful and useful WordPress function query_posts() breaks several other features like search, next post/previous post, and maybe more. Ugh.

A client wanted their blog post page to show entries only from the current calendar week starting on Monday. So if it was Thursday, the index page would show posts from the last four days, Monday-Thursday. If there ever was a mission for query_posts(), this was it.

$weekstart = date("W");
query_posts('w='.$weekstart);

(Put that above The Loop. It uses PHP’s date() function to get the current calendar week’s first day, which by definition and luck happens to be Monday.)

Fine, but hold on: search broke. A search would return nothing. Who was the culprit? Why it’s query_posts(). I was shocked, shocked (sarcasm).

Here’s how I got around it: I figured if I could make search use another template, one without the offending function, I’d be fine. I looked into that but didn’t find much (didn’t spend too much time looking though). Then I had a better idea: don’t move search, move the index page.

  1. create a new template with your troublemaking query_posts() on it, name it Home
  2. create a new page, give it the Home template
  3. in Admin -> Settings -> Reading set Front Page Displays Static Page -> Home
  4. return the template file index.php to its original state, or at least take off query_posts()

That’s it. Search works because it’s not using the offending template. Home works becuase I get to keep query_posts() on it to display the week’s posts like the client wants. Everybody’s happy.

Tags: , ,