htmlをパターンの数だけ作成
別々のogp、twitterカードを設定したhtmlを用意(4パターンなら4つ用意)。
このページ自体は表示するコンテンツがないので、location.href='./';
でトップページへリダイレクトする。
product1.html
<!-- ogp -->
<meta property="og:title" content="商品1のたいとる">
<meta property="og:url" content="http://sample.com/product1.html">
<meta property="og:image" content="http://sample.com/img/ogp/1.png">
<meta property="og:description" content="商品1のでぃすくりぷしょん">
<!--(中略)-->
<!-- twitter card -->
<meta property="twitter:image" content="http://sample.com/img/ogp/1.png">
<meta name="twitter:description" content="商品1のでぃすくりぷしょん" />
<script>
location.href = './'; // リダイレクト
</script>
クリックされるボタンに応じてurlの違うaタグを作成。
index.pug
- const url_1 = url + 'product1' + '.html';
- const encode_description_1 = encodeURIComponent(description_1)
//-(中略)
.socialButton--twitter.
<a href="http://twitter.com/intent/tweet?text=#{encode_description_1}&url=#{url_1}&hashtags=#{encode_hashtag}&via=#{encode_via}" target="_blank"></a>
rails環境だったらこんな感じか
index.html.slim
.socialButton--twitter
a(href="http://twitter.com/intent/tweet?text=#{URI.encode(product.discription)}&url=#{Settings.site.url + '/' + product.name + '.html'}&hashtags=#{URI.encode(Settings.site.meta.twitter.hashtags)}" target="_blank")
クリックされるボタンに応じてhrefを切り替える。
socialScript.pug
# fb-root
script.
window.fbAsyncInit = function() {
FB.init({
appId : '#{facebook_app_id}',
xfbml : true,
version : 'v2.8'
});
};
function shareFB(ogp_id){
var ogp_href = (ogp_id) ? '#{url}' + ogp_id + '.html' : '#{url}' ;
FB.ui({
method: 'share',
href: ogp_href,
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/ja_JP/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
var facebookButtons = document.getElementsByClassName('js-facebookButton');
for (var i = 0; i < facebookButtons.length; i++) {
facebookButtons[i].addEventListener('click', function(){
var ogp_id = this.getAttribute('ogp-id');
shareFB(ogp_id);
}, false)
}