先前介紹過如何在WordPress的AMP頁面配置相關文章與分享按鈕,
這回將介紹如何在AMP頁面載入Disqus評論框,
與Disqus Conditional Load外掛同樣採取延遲載入的方式不會拖慢網頁性能,
透過amp-iframe框架進行設定,
需要使用其他子域名進行託管AMP版Disqus頁面方可正常載入評論框。
Disqus AMP官方消息 https://blog.disqus.com
Disqus AMP官方安裝說明 https://github.com/disqus
請在WordPress當前使用的佈景主題資料夾底下建立amp資料夾,
從AMP外掛模板複製single.php到資料夾中,
請在</head>前方寫入
<script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"> </script>
接下來將以下代碼複製並建立成新的html檔案
<div id="disqus_thread"></div>
<script>
window.addEventListener('message', receiveMessage, false);
function receiveMessage(event)
{
if (event.data) {
var msg;
try {
msg = JSON.parse(event.data);
} catch (err) {
// Do nothing
}
if (!msg)
return false;
if (msg.name === 'resize') {
window.parent.postMessage({
sentinel: 'amp',
type: 'embed-size',
height: msg.data.height
}, '*');
}
}
}
</script>
<script>
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var disqus_config = function () {
this.page.url = decodeURIComponent(getQueryVariable("url")); // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = decodeURIComponent(getQueryVariable("identifier")); // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//disqususer.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>請將//disqususer.disqus.com/embed.js的disqususer修改成您站點使用的disqus域名,
並保存到其他域名的站點,其他站點不能與原本要加載DisqusAMP的站點域名相同。
接下來,請在WordPress當前使用的佈景主題底下佈景函式庫functions.php加入以下代碼
if ( ! function_exists( 'add_disqus' ) ) {
function add_disqus( $content ) {
if(is_amp_endpoint()) {
$post = get_post();
$content .= '
<amp-iframe width=600 height=140
layout="responsive"
sandbox="allow-scripts allow-same-origin allow-modals allow-popups"
resizable
frameborder="0"
src="https://otherurl/disqus-amp.html?url='.urlencode(get_permalink()).'&identifier='.urlencode($post->ID).'"
>
<div overflow tabindex=0 role=button aria-label="Comentários">Comentários</div>
</amp-iframe>';
}
return $content;
}
}
add_action( 'the_content', 'add_disqus' );其中https://otherurl/disqus-amp.html即為上個步驟產生html檔案存放的其他域名,
保存後即可在AMP頁面測試Disqus載入情形,
如果沒有載入成功請在 https://disqus.com/admin/settings/advanced/
允許其他域名載入評論內容,
並檢查headers的X-Frame-Options是否允許自其他域名載入,
若Disqus AMP評論框順利載入即完成配置。
參考教學 https://github.com/disqus
WordPress AMP配置Disqus評論功能
