single.php is called twice – how to stop

Stop double content rendering

Stop double execution

single.php is called twice for every post view – that was my conclusion after some investigations. How I’ve got it?
Trying to build the list of recently viewed posts I added simple tracking code into my active “Twenty Eleven” theme single.php template file. After that I’was wondered as I’ve got two records in my log instead the only one after any post view. First valid record for just viewed post and second unexpected record for post, which is chronologically next to the viewed post.
Thus WordPress post content rendered at least twice every time visitor clicks on its permalink. It is obvious and unneeded overhead for my opinion. Why it is happened? How to stop this weird behaviour?
Quick tests in PHP debugger did not bring the light on the problem. WordPress doesn’t belong to software which debugging is easy. A lot of filters and actions, which make WordPress so powerful and extensible thing, make it more complex to understanding of code execution logic, as it is not linear some time. I went through WordPress execution cycle from begin to end then automatically the same way once again, without visible reason.
Permalink? Let’s check the idea. I had permalink ‘post name’ selected and active by default. When I turned it off, I resolved my problem. But I need the other way as I don’t agree to reject from SEO-friendly permalinks using.

WordPress is very popular blog platform and I’m not the first and the only man who met such problem. Thus Google search helped me. I found a couple of discussions on the subject:
1. single.php called for current and next post with pretty permalinks;
2. Problem with add_filter while developing plugin.

The reason is that WordPress renders full post content using theme template to preload chronologically next post to the cache and get its valid permalink. Little change to make code compatible with the latest WordPress version 3.4.2 gave me this solution:

 // stop next post preloading and thus single.php calling twice
 remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');

Add this line to your theme functions.php file to avoid the problem with single.php twice execution.

If you meet the same problem with double content rendering, but don’t wish to change anything at your theme you may achieve the same via plugin. Extract PHP file from this archive, place it into your blog wp-content/plugins/ folder and activate new added plugin. It has no options and make its work in silence. Other way to execute code from this plugin is to place it into wp-content/mu-plugins directory. Then it will work even without activation (‘mu’ at ‘mu-plugins’ means ‘Must Use’).

P.S. If you find any side effect of this enhancement, please share your experience with us.

Tags: