問題 × 解決策

WordPressで特定の記事に独自のjavascriptを設定する方法

問題

Wordpressで特定の記事に独自のjavascriptを設定したい。

解決策

テーマ内の「functions.php」で、投稿タイプに対してjavascript記述用のカスタムフィールドを作成して適用させる。

 

特定の記事のみに独自のjavascriptを設定する。

WordPressで特定の記事のみに独自のjavascriptを設定したいという場面は多いのではないでしょうか。
共通のjavascriptファイルにそれを記述してしまうとキリがなくなってしまう上に、スクリプト同士で処理が競合してしまう危険性も…。
そんな場合用に、独自のjavascriptを設定する方法をご紹介します。

テーマ内の「functions.php」に、記述を行います。

テーマ内の「functions.php」に、以下の記述を行います。

functions.php

add_action( 'admin_menu', 'custom_js_hooks' );
add_action( 'save_post', 'save_custom_js' );
add_action( 'wp_footer','insert_custom_js' );
function custom_js_hooks() {
  add_meta_box( 'custom_js', 'Custom JS', 'custom_js_input', '投稿タイプのスラッグ', 'normal', 'high' );
}
function custom_js_input() {
  global $post;
  echo '<input type="hidden" name="custom_js_noncename" id="custom_js_noncename" value="'.wp_create_nonce('custom-js').'" />';
  echo '<textarea name="custom_js" id="custom_js" rows="5" cols="30" style="width:100%;">'.get_post_meta($post->ID,'_custom_js',true).'</textarea>';
}
function save_custom_js($post_id) {
  if (!wp_verify_nonce(@$_POST['custom_js_noncename'], 'custom-js')) return $post_id;
  if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
  $custom_js = $_POST['custom_js'];
  update_post_meta($post_id, '_custom_js', $custom_js);
}
function insert_custom_js() {
  if ( is_page() || is_single() ) {
	  $js_custom = get_post_meta(get_the_ID(), '_custom_js', true);
	  if(!empty($js_custom)): echo '<script type="text/javascript">' . $js_custom . '</script>'; endif;
	  /*
    if ( have_posts() ) : while ( have_posts() ) : the_post();
      echo '<script type="text/javascript">' . get_post_meta(get_the_ID(), '_custom_js', true) . '</script>';
    endwhile; endif;
    rewind_posts();
	*/
  }
}

参考

【WordPressで記事個別や固定ページ単体にCSS・JavaScriptを追加する(プラグインなし) | 賢威カスタマイズ研究所】
http://www.keni-customize.net/css-javascript-noplugin-536/

コメント

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

20 + 4 =

「問題 × 解決策」
月別アーカイブ一覧

「問題 × 解決策」
月別アーカイブ一覧