WordPressで固定ページや投稿記事ごとに、ヘッダ<head></head>内に記述を追加できるようにするカスタマイズメモです。例えば、それぞれのページ、投稿で個別にmeta要素やCSS、JavaScriptを追加したい時に役立ちます。
外部CSSやJavaScriptファイルの呼び出しもできますし、スタイルやJavaScriptを直接ヘッダに記述したい場合にも便利です。以下で紹介する方法はfunctions.phpを使用しますので、テーマ内にfunctions.phpがない場合は作成してください。
[adsense]投稿画面にAdd to headウィジェットを作成
function.php
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', 'Add to head', 'add_head_input', 'post', 'normal', 'high');
add_meta_box('add_head', 'Add to 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 '<!--Add to head-->'.get_post_meta(get_the_ID(), '_add_head', true).'<!--/Add to head-->';
endwhile; endif;
rewind_posts();
}
}
以上をfunction.phpに記述することで、投稿編集画面にAdd to headウィジェットが表示される筈です。
<!–Add to head–> <!–/Add to head–>のコメントアウト部分は、無くてもかまいません。ウィジェット内に何も記述しない場合は、コメントアウトの部分だけがヘッダに追加されます。
※この記事のカスタマイズ方法はWordPressバージョン3.4.2で検証したものです。

[…] WordPressで記事ごとにヘッダの記述を追加する方法 […]