Adding disqus support to ghost without custom templates

Jul 27 2018

I wanted to add disqus support to ghost. The official way is to update your current theme. But I rather prefer not to touch it so it gets updated automatically. So I decided to write some custom JavaScript code and embed it using the standard ghost Code Injection.

The idea is first to differentiate posts from other pages. You can query the post-full class name, and execute code in the case it exists. Later, you can query the link[rel=canonical].href to get the canonical url, and you can parse it to get the last part of the url as it is the slug and the identifier of the page. Then you can inject a <div id="disqus_thread"> as last child of the article.post-full, and inject the discus code after that.

<script type="text/javascript">
    const postFull = document.getElementsByClassName('post-full')[0];
    if (postFull) {
        // @TODO: EDIT THIS
        const DISQUS_ID = 'YOUR_DISQUS_ID'; 
        
        const canonical = document.head.querySelector('link[rel=canonical]').href;
        const extractIdRegex = /\/([^\/]*)\/?$/;
        const div = document.createElement('div');
        const identifier = canonical.match(extractIdRegex)[1] || canonical;
        window.canonical = canonical;
        window.identifier = identifier;
        div.id = 'disqus_thread';
        postFull.appendChild(div);
        
        var disqus_config = function () {
            this.page.url = canonical;
            this.page.identifier = identifier;
        };
        
        (function() { // DON'T EDIT BELOW THIS LINE
            var d = document, s = d.createElement('script');
            s.src = 'https://' + DISQUS_ID + '.disqus.com/embed.js';
            s.setAttribute('data-timestamp', +new Date());
            (d.head || d.body).appendChild(s);
        })();
    }
</script>

And guess what? It works pretty well.