2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

複数のOGP・TwitterCardsを出し分ける

Last updated at Posted at 2016-05-16

htmlをパターンの数だけ作成

別々のogp、twitterカードを設定したhtmlを用意(4パターンなら4つ用意)。
このページ自体は表示するコンテンツがないので、location.href='./';でトップページへリダイレクトする。

FfzFdPX6rO.html
<!-- ogp-->
<meta property="og:url" content="http://sample.com/FfzFdPX6rO.html">
<meta property="og:image" content="http://sample.com/img/ogp1.png">

<!--(中略)-->

<!-- twitter card-->
<meta property="twitter:image" content="http://sample.com/img/ogp1.png">

<!--(中略)-->

<div id="fb-root"></div>
<script>(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#xfbml=1&version=v2.6";fjs.parentNode.insertBefore(js, fjs);}(document, 'script', 'facebook-jssdk'));</script>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>

<script>
  location.href = './'; // リダイレクト
</script>

その他のmetaタグの設定も忘れず。

twitter

urlの違うaタグを作成

index.jade
- var ogpAry = ['FfzFdPX6rO', 'Htga89sPna', 'Tr7ad4G6we', 'oPYrea82Mh'];
- var encode_siteurl1 = encodeURIComponent(site_url + ogpAry[0] + '.html');

//-(中略)
.btn-twitter.btn-social.
  <a href="http://twitter.com/intent/tweet?text=#{encode_description}&amp;url=#{encode_siteurl1}&amp;hashtags=#{encode_hashtag}&amp;via=#{encode_via}" target="_blank"></a>


facebook

クリックされるボタンに応じてhrefを切り替える。

facebook.js
window.fbAsyncInit = function() {
  FB.init({
    appId      : 'xxxxxxxxxx',
    xfbml      : true,
    version    : 'v2.6'
  });
};
var ogpAry = ['FfzFdPX6rO', 'Htga89sPna', 'Tr7ad4G6we', 'oPYrea82Mh'];
function shareFB(ogpID){
  var ogpHref = 'http://sample.com/' + ogpAry[ogpID - 1] + '.html';
  FB.ui({
      method: 'share',
      href: ogpHref,
    });
};
(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'));

$('.js-share_fb').on('click', function(){
  var $ogp_id = $(this).data('ogp-id');
  shareFB($ogp_id);
});
2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?