前言

之前在 Jekyll 時有串 Disqus 近來讓每篇文章底下有留言板的功能,後來搬移到 Hexo 的時候,用法不一樣所以會出錯,就暫時把他移除掉,最近閒來無事又想把他加進來XD

Disqus

Disqus 的留言板服務在不少網站上滿常見的,外觀也很好辨認,而且行之有年了

Get started

首先,就是去官網辦一個帳號,然後登入,接著在首頁的地方 Get Started,就會看到以下頁面

選擇 I want to install Disqus on my site

印象中會先跳去一個建議付費方案的頁面,可以跳過他然後直接進入設定

Create site

在 Website Name 的欄位填入的名字會是你的 site short name,會在之後 Hexo 的設定用到

Category 的部分就看個人選擇

Configure

Website Name 的地方放入你想取的名字,在 Website URL 的地方填上你的部落格位址

上方的 Shortname 不能再更改,底下還有其他一些設定看個人喜好

建好後可以在個人頁面左上角的地方看到 Your site,點進去就會到設定頁面

Delete

如果想要移除,在 Configure 頁面的左邊的 side menu,點選 Advanced,就能刪除目前的 site 了

加到 Hexo

其實 Hexo demo 的 landscape theme 有支援 Disqus 留言板插件,所以我的做法就是去 landscape theme 裡面把需要的東西搬過來

如果本身已經是 landscape theme 的話就只要在 config 內做好設定就能成功啟用了

config

先在 _config.yml 放入字串設定

disqus_enabled 是為了方便全域啟用或停用而加的,如果是 landscape theme,只要加入 disqus_shortname 就可以了

1
2
3
# Disqus comments
disqus_enabled: true
disqus_shortname: your-short-name

landscape theme usage

找到 layout/_partial/after-footer.ejs 這個檔案,把它複製然後移到自己檔案對應的目錄下

稍做更動,在條件的地方多加入 disqus_enabled

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// after-footer.ejs
<% if (config.disqus_enabled && config.disqus_shortname){ %>
<script>
var disqus_shortname = '<%= config.disqus_shortname %>';
<% if (page.permalink){ %>
var disqus_url = '<%= page.permalink %>';
<% } %>
(function(){
var dsq = document.createElement('script');
dsq.type = 'text/javascript';
dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/<% if (page.comments) { %>embed.js<% } else { %>count.js<% } %>';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<% } %>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<% if (theme.fancybox){ %>
<%- css('fancybox/jquery.fancybox') %>
<%- js('fancybox/jquery.fancybox.pack') %>
<% } %>

layout.ejs

layout/layout.ejs 中加入 after-footer

1
2
3
4
5
6
7
8
// layout.ejs
...
</div>
<%- partial('_partial/footer',{cache: true}) %>
<%- partial('_partial/after-footer') %>
</div>
</body>
</html>

post.ejs

接著就是要讓每篇文章底下都有 Disqus 留言板

觀察一下 landscape theme 是怎麼做的,可以根據個人使用的 theme 而定

我的話是在 layout/_page/post.ejs 中的底部塞入以下程式碼

1
2
3
4
5
6
7
8
9
10
11
...
<div>
<% if (!index && post.comments && config.disqus_enabled && config.disqus_shortname){ %>
<section id="comments">
<div id="disqus_thread">
<noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
</section>
<% } %>
</div>
</article>

這邊注意到 post.comments 這個屬性,在 Hexo default 他是 true,所以在 Front-Matter 內沒有設置的話,預設就會是開啟留言

到這邊就大功告成了,可以在 local 測試一下有沒有成功加入 Disqus 留言板功能囉