2015年05月13日(Wed)

プラグインを使わずウィジェットを作成してページ別にMETAタグなどを追加する方法
cssやjavascriptのファイルをページ別で読み込みたいとプラグインを探していたら、プラグインを使わずにfunctions.phpにコードを記述してAdd to headと呼ばれているウィジェットを作成するだけで簡単にできる方法を見つけました。 METAタグやコードの記述を追加したい場合に便利ですね。
functions.php にコードを記述
functions.phpに下記のコードを記述すると投稿や固定ページの編集画面に「headに追加」の入力欄が出現します。 そこに、METAタグやちょっとしコードの記述などが可能となります。
functions.php
//記事別にhead内に追加
add_action('admin_menu', 'add_head_hooks');
add_action('save_post', 'save_add_head');
add_action('wp_head','insert_add_head');
function add_head_hooks() {
add_meta_box('add_head', 'headに追加', 'add_head_input', 'post', 'normal', 'high');
add_meta_box('add_head', 'headに追加', 'add_head_input', 'page', 'normal', 'high');
}
function add_head_input() {
global $post;
echo '<input type="hidden" name="add_head_noncename" id="add_head_noncename" value="'.wp_create_nonce('add-head').'" />';
echo '<textarea name="add_head" id="add_head" rows="5" cols="30" style="width:100%;">'.get_post_meta($post->ID,'_add_head',true).'</textarea>';
}
function save_add_head($post_id) {
if (!wp_verify_nonce($_POST['add_head_noncename'], 'add-head')) return $post_id;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
$add_head = $_POST['add_head'];
update_post_meta($post_id, '_add_head', $add_head);
}
function insert_add_head() {
if (is_page() || is_single()) {
if (have_posts()) : while (have_posts()) : the_post();
echo get_post_meta(get_the_ID(), '_add_head', true);
endwhile; endif;
rewind_posts();
}
}
読み込むファイルは絶対パスで!
CSSやJavaScriptのファイルを読み込むときは、絶対パスで記述する事がお勧めとの事です。
どうやら、相対パスではうまく機能しないようです。
【参考Webサイト】
コメント(0件)
プラグインを使わずウィジェットを作成してページ別にMETAタグなどを追加する方法に対するご意見、ご感想、情報提供など皆様からのコメントをお待ちしております。 お気軽にコメントしてください。

コメントフォーム