Wordpress and disqus and post loops

If you enjoyed this article, please leave a comment, rss subscribe to my RSS feed and/or follow me on Twitter. Thank you very much!

First off — I don't have too much experience with disqus on Wordpress but when I looked at the code(-quality), disqus is one of the best plugins for Wordpress to date. I looked only very briefly, but I found it to be very clean, well documented and well architected. Good job, disqus!

In case you happen to dive into Wordpress plugins in 2012, you will see that this is unfortunately not a given. Even (or maybe especially) the commercially available plugins to extend Wordpress are a source for PHP worst practices and contain all kinds of examples how not to write PHP. Part of it, is the platform, the rest is unexperienced developers or general lazyness.

Anyhow! Enough the rant!

Disqus and the loop

In Wordpress, almost everything is a loop. If you'd like to display a list of posts somewhere (for whatever reason), a loop is executed. The advantage (vs. a straight SQL query) range from all kinds all things like caching to convenience. When said hook is used different actions (plugin hooks) and filters are run. So even when the objective is to just collect data (and not even display it) — for example for an Ajax request/response — all these things happen in the back.

So in this case, whenever a loop is used, disqus will attempt to add their JavaScript to it. Usually, to display a comment form, counts and what not.

Problem?

The problem is, that the JavaScript code is then added all over and especially with Ajax you end up with the same code multiple times but add to that the cost of transport.

Solution!

Here's a simple workaround to prevent that.

Stick the following code into your template when you do not want the code to appear:

<?php
if (has_action('loop_end', 'dsq_loop_end')) {
    remove_action('loop_end', 'dsq_loop_end');
}

Yay! Happyness!

Fin

Filters and hooks are really what make Wordpress worth while. Period. In case you happen to do development for it, I urge you to take a look at them. I have a couple more ideas for small posts — stay tuned.

| More