Why is WordPress redirecting users to random posts after commenting?

After commenting on one of my posts, WordPress redirects me to another random post. Only after, when checking the previous post, I can see that my comment was posted. Still, why is WordPress sending me to a random post after commenting?

Here’s my comments.php file and here’s my website (please don’t publish it anywhere else, as I’m launching it tomorrow). Feel free to test the comments, though. I’ll clear then before I launch it. Any suggestions?

PS: I’m using no plugins and the bug doesn’t work on other themes. Also, I’m using pretty /%postname%/ permalinks.

3 Answers

You’re doing something that is affecting the value of the main $post variable in an incorrect manner.

The WordPress template consists of one main Loop. That Loop, on a single post page, shows the one and only Post (or Page).

When the comments form runs, it expects the last post from the Loop to be the one you’re commenting on. However, if you mess with the main Loop after the fact (like by doing another query_posts() or altering the global $post variable in any way), then you’ll muck that bit up. This is what is happening on your posts.

If you look at the source of http://joaoramos.org/sala-de-ser/ you’ll see that that post’s ID number is 635, but the comments form thinks it’s 630. I’m surprised the comments go to the right pages.

Specifically, what is happening here is that your sidebar is doing-it-wrong™. If you’ll notice, the last entry in your sidebar is for http://joaoramos.org/via/ which, BTW, is post number 630.

When you make secondary Loops, you should create new WP_Query objects instead of modifying the main one and your loop shouldn’t modify any global variables, if possible.

No quick fix to this one. Rewrite your sidebar to not muck up the main Loop.

Edit: Didn’t know about this one. Just add a call to wp_reset_postdata() after the sidebar loops run to fix up the global $post information back to what it should be.

Leave a Comment