Twitter等をブログに貼り付ける時のscriptタグを自動で1つにする方法

  • 投稿 : 2015-09-08
scriptタグが1個で良い場合は、ツートの埋め込み以外でも応用できるかと思います。

Twitter

//---------------------------------------------------------
// スクリプトを読むのを1回にする
//---------------------------------------------------------
function content_script($text){
   $subject = $text;
   $script ='<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>';
   $pattern='!'.preg_quote($script,"!").'!';

   if(is_single() && preg_match($pattern,$subject )){
      $pattern='!('.preg_quote($script,"!").')!';
      $replacement ="";
      $text =preg_replace($pattern ,$replacement ,$subject);
      $text = $text .$script;
   }
   return $text;
}
add_filter('the_content', 'content_script');
テーマのfunctions.phpに上記を追加

参考:
えふすくBlog いろいろ実験室: Twitterの埋め込みのときscriptタグは1つでいいらしい件
知らんかった…複数のツイートをブログに挿入するときに気をつけたい1つのこと | てきとーだろ?

はてぶコメント

//---------------------------------------------------------
// スクリプトを読むのを1回にする
//---------------------------------------------------------
function content_script($text){
   $subject = $text;
  $script ='<script src="https://b.st-hatena.com/js/comment-widget.js" charset="utf-8" async></script>';
   $pattern='!'.preg_quote($script,"!").'!';

   if(is_single() && preg_match($pattern,$subject )){
      $pattern='!('.preg_quote($script,"!").')!';
      $replacement ="";
      $text =preg_replace($pattern ,$replacement ,$subject);
      $text = $text .$script;
   }
   return $text;
}
add_filter('the_content', 'content_script');

Twitterのサンプルの$script部分だけを書き換えてるだけです。
スポンサーリンク