WordPressのTwenty Elevenテーマ解説:サイドバー (sidebar.php)
WordPressの勉強も兼ねて、Twenty Elevenテーマの各テンプレートについて解説しています。確認バージョンは3.2.1です。
サイドバー (sidebar.php)
Twenty Elevenテーマの「サイドバー (sidebar.php)」は、次のように、各ページのサイドバーを表示します。
テンプレートのソースコードは次のとおりです。
<?php
/**
* The Sidebar containing the main widget area.
*
* @package WordPress
* @subpackage Twenty_Eleven
* @since Twenty Eleven 1.0
*/
$options = twentyeleven_get_theme_options();
$current_layout = $options['theme_layout'];
if ( 'content' != $current_layout ) :
?>
<div id="secondary" class="widget-area" role="complementary">
<?php if ( ! dynamic_sidebar( 'sidebar-1' ) ) : ?>
<aside id="archives" class="widget">
<h3 class="widget-title"><?php _e( 'Archives', 'twentyeleven' ); ?></h3>
<ul>
<?php wp_get_archives( array( 'type' => 'monthly' ) ); ?>
</ul>
</aside>
<aside id="meta" class="widget">
<h3 class="widget-title"><?php _e( 'Meta', 'twentyeleven' ); ?></h3>
<ul>
<?php wp_register(); ?>
<li><?php wp_loginout(); ?></li>
<?php wp_meta(); ?>
</ul>
</aside>
<?php endif; // end sidebar widget area ?>
</div><!-- #secondary .widget-area -->
<?php endif; ?>
以下、順を追ってテンプレートの内容について解説します。
1.レイアウト情報の取得
テーマ情報をtwentyeleven_get_theme_options()で取得し、さらにその中のレイアウト情報を取得します。
$options = twentyeleven_get_theme_options();
$current_layout = $options['theme_layout'];
twentyeleven_get_theme_options()はwp-content/themes/twentyeleven/inc/theme-options.phpに実装されています。
wp-content/themes/twentyeleven/inc/theme-options.php
function twentyeleven_get_theme_options() {
return get_option( 'twentyeleven_theme_options', twentyeleven_get_default_theme_options() );
}
twentyeleven_get_theme_options()の中ではget_option()を実行しているだけです。get_option()の第1パラメータはオプション名、第2パラメータはデータベースにオプションが存在しない場合のデフォルト値です。デフォルト値はtwentyeleven_get_default_theme_options()で返却された値を使用しています。
twentyeleven_get_default_theme_options()は、twentyeleven_get_theme_options()と同じtheme-options.phpに実装されています。
function twentyeleven_get_default_theme_options() {
$default_theme_options = array(
'color_scheme' => 'light',
'link_color' => twentyeleven_get_default_link_color( 'light' ),
'theme_layout' => 'content-sidebar',
);
if ( is_rtl() )
$default_theme_options['theme_layout'] = 'sidebar-content';
return apply_filters( 'twentyeleven_default_theme_options', $default_theme_options );
}
$options['theme_layout']に対応する内容として「content-sidebar」が設定されていることが分かります。
2.レイアウトについて
Twenty Elevenテーマのレイアウトには次の3種類が用意されています。
- content-sidebar(右サイドバー)
- sidebar-content(左サイドバー)
- content(サイドバーなし)
レイアウトは、theme-options.phpのtwentyeleven_layouts()に定義されています。
function twentyeleven_layouts() {
$layout_options = array(
'content-sidebar' => array(
'value' => 'content-sidebar',
'label' => __( 'Content on left', 'twentyeleven' ),
'thumbnail' => get_template_directory_uri() . '/inc/images/content-sidebar.png',
),
'sidebar-content' => array(
'value' => 'sidebar-content',
'label' => __( 'Content on right', 'twentyeleven' ),
'thumbnail' => get_template_directory_uri() . '/inc/images/sidebar-content.png',
),
'content' => array(
'value' => 'content',
'label' => __( 'One-column, no sidebar', 'twentyeleven' ),
'thumbnail' => get_template_directory_uri() . '/inc/images/content.png',
),
);
return apply_filters( 'twentyeleven_layouts', $layout_options );
}
レイアウトを変更するには、管理画面の「外観」→「テーマ設定」→「デフォルトのレイアウト」で行えます。
3.レイアウトの判定
取得したレイアウトの判定を行い、「content」つまりサイドバーを表示しないレイアウト以外であれば、ifブロック内を実行します。
<?php
…中略…
if ( 'content' != $current_layout ) :
?>
…中略…
<?php endif; ?>
4.サイドバーの判定
dynamic_sidebar()でサイドバーの有無を判定します。第1パラメータはサイドバーの名称で「sidebar-1」は管理画面の「外観」→「ウィジェット」の「メインサイドバー」が対応します。「メインサイドバー」にウィジェットが1つも割り当てられていなけばifブロック内を実行します。
<div id="secondary" class="widget-area" role="complementary">
<?php if ( ! dynamic_sidebar( 'sidebar-1' ) ) : ?>
…中略…
<?php endif; // end sidebar widget area ?>
</div><!-- #secondary .widget-area -->
dynamic_sidebar()はwp-includes/widgets.phpに実装されています(掲載は割愛)。この関数の実行結果は真偽値を返却します。
5.アーカイブ一覧の出力
次の部分でアーカイブ一覧を出力します。
<aside id="archives" class="widget">
<h3 class="widget-title"><?php _e( 'Archives', 'twentyeleven' ); ?></h3>
<ul>
<?php wp_get_archives( array( 'type' => 'monthly' ) ); ?>
</ul>
</aside>
wp_get_archives()は日付ベースのアーカイブリストを表示するテンプレートタグで、wp-includes/general-template.phpに実装されています(掲載は割愛)。
パラメータの「type」には次のものを指定できます。指定を省略した場合は「monthly」を適用します。
- yearly
- monthly
- daily
- weekly
- postbypost
その他、下記のパラメータを設定できます(内容は公式ドキュメントより)。
- limit:取得するアーカイブ数を数値で設定。デフォルトは制限なし
- format:アーカイブリストの形式(下記のいずれか)を設定
- html:HTML のリストタグ(<li>)と before・after の文字列
- option:セレクトボックスまたはドロップダウンメニュー用のセレクトタグ(<select>)内のオプションタグ(<option>)
- link:リンクタグ(<link>)内に
- custom:before・after の文字列を用いたカスタムリスト
- before:リンクの前に表示する内容(htmlまたはcustomを選択した場合に有効)
- after:リンクの後に表示する内容(htmlまたはcustomを選択した場合に有効)
- show_post_count:投稿数を表示(真偽値を設定)
6.メタ情報の出力
次の部分でアーカイブ一覧を出力します。
<aside id="meta" class="widget">
<h3 class="widget-title"><?php _e( 'Meta', 'twentyeleven' ); ?></h3>
<ul>
<?php wp_register(); ?>
<li><?php wp_loginout(); ?></li>
<?php wp_meta(); ?>
</ul>
</aside>
wp_register()は次の制御を行います。
- ログイン中:「サイト管理」のリンクを出力(クリックすれば管理画面に移動)
- ログアウト中:
- 管理画面の「設定」→「一般」の「だれでもユーザー登録ができるようにする」をチェックしている場合:「登録」のリンクを出力
- チェックしていない場合:何も出力しない
ログイン中の表示

ログアウト中(または他ユーザー)でチェックしている場合の表示

wp_register()はwp-includes/general-template.phpに実装されています。
wp-includes/general-template.php
function wp_register( $before = '<li>', $after = '</li>', $echo = true ) {
if ( ! is_user_logged_in() ) {
if ( get_option('users_can_register') )
$link = $before . '<a href="' . site_url('wp-login.php?action=register', 'login') . '">' . __('Register') . '</a>' . $after;
else
$link = '';
} else {
$link = $before . '<a href="' . admin_url() . '">' . __('Site Admin') . '</a>' . $after;
}
if ( $echo )
echo apply_filters('register', $link);
else
return apply_filters('register', $link);
}
wp_loginout()はログインリンクを表示します。ログインしているユーザーにはログアウトリンクを表示します。
ログイン中

ログアウト中

wp_loginout()はwp-includes/general-template.phpに実装されています。
wp-includes/general-template.php
function wp_loginout($redirect = '', $echo = true) {
if ( ! is_user_logged_in() )
$link = '<a href="' . esc_url( wp_login_url($redirect) ) . '">' . __('Log in') . '</a>';
else
$link = '<a href="' . esc_url( wp_logout_url($redirect) ) . '">' . __('Log out') . '</a>';
if ( $echo )
echo apply_filters('loginout', $link);
else
return apply_filters('loginout', $link);
}
wp_meta()は、プラグインのアクションフックです。デフォルトの状態では何も出力されません。functions.phpに次のようなコードを記述すればリンクが表示されます。
function out_link () {
echo "<li><a href="...">foo</a></li>";
}
add_action('wp_meta', 'out_link');
WordPressのTwenty Elevenテーマ解説:固定ページテンプレート (page.php)
WordPressの勉強も兼ねて、Twenty Elevenテーマの各テンプレートについて解説しています。確認バージョンは3.2.1です。
固定ページテンプレート (page.php)
Twenty Elevenテーマの「固定ページテンプレート (page.php)」で出力されるページは次のように、URLが一意のページにコンテンツが表示されます。
テンプレートのソースコードは次のとおりです。
<?php
/**
* The template for displaying all pages.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site will use a
* different template.
*
* @package WordPress
* @subpackage Twenty_Eleven
* @since Twenty Eleven 1.0
*/
get_header(); ?>
<div id="primary">
<div id="content" role="main">
<?php the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php comments_template( '', true ); ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_footer(); ?>
以下、順を追ってテンプレートの内容について解説します。「WordPressのTwenty Elevenテーマ解説:単一記事の投稿 (single.php)」と重複している部分がありますが、この記事だけで一気に読みきれるよう、他の記事への参照は行ってません。
1.ヘッダー情報の出力
ヘッダー情報はget_header()で出力します。
<?php
…中略…
get_header(); ?>
ヘッダー情報は赤枠部分が対応します。
get_header()はwp-includes/general-template.phpに実装されています。
wp-includes/general-template.php
function get_header( $name = null ) {
do_action( 'get_header', $name );
$templates = array();
if ( isset($name) )
$templates[] = "header-{$name}.php";
$templates[] = 'header.php';
// Backward compat code will be removed in a future release
if ('' == locate_template($templates, true))
load_template( ABSPATH . WPINC . '/theme-compat/header.php');
}
do_action()はフックポイント「get_header」の作成を行っています。
do_action( 'get_header', $name );
プラグインを作成している方はすでにご存知と思いますが、add_action()を使えばフックポイントに任意のアクションを追加できます。
例えばプラグインで次のコードを記述すれば、フックポイント「get_header」、つまりdo_action('get_header')の実行時にfoo()が起動され、doctype宣言の前に「foo」が出力されます。
<?php
/*
Plugin Name: Foo
Description: Foo
Version: 1.0
*/
function foo() {
echo "foo";
}
add_action('get_header', 'foo');
?>
話を戻して、get_header()では、パラメータに設定した文字列をテンプレート名として利用します。「get_header('foo')」と書いておけば、「header-foo.php」を「header.php」の代わりにロードします。パラメータの設定がなければ「header.php」をロードします。
$templates = array();
if ( isset($name) )
$templates[] = "header-{$name}.php";
$templates[] = 'header.php';
2.記事データの取得
赤色で示したthe_post()で、記事データを取得します。
<div id="primary">
<div id="content" role="main">
<?php the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php comments_template( '', true ); ?>
</div><!-- #content -->
</div><!-- #primary -->
the_post()は投稿データをロードする関数で、wp-includes/query.phpに実装されています。the_post()を実行しただけでは何も出力しません。
wp-includes/query.php
function the_post() {
global $wp_query;
$wp_query->the_post();
}
3.コンテンツの出力
赤色のget_template_part()でコンテンツを出力します。
<div id="primary">
<div id="content" role="main">
<?php the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php comments_template( '', true ); ?>
</div><!-- #content -->
</div><!-- #primary -->
コンテンツは次の赤枠部分が該当します。
get_template_part()はwp-includes/general-template.phpに実装されています。
wp-includes/general-template.php
function get_template_part( $slug, $name = null ) {
do_action( "get_template_part_{$slug}", $slug, $name );
$templates = array();
if ( isset($name) )
$templates[] = "{$slug}-{$name}.php";
$templates[] = "{$slug}.php";
locate_template($templates, true, false);
}
do_action()でフックポイント「get_template_part_スラッグ名」の作成を行っています。この場合はスラッグ名は「content」なので、フックポイント名は「get_template_part_content」になります。
また、get_header()と同様、第1パラメータと第2パラメータに設定された名前を使ってテンプレートを呼び出します。第2パラメータが設定されていれば、「スラッグ名-名前.php」でテンプレートを呼び出します。第2パラメータが設定されていなければ、「スラッグ名.php」でテンプレートを呼び出します。
固定ページテンプレート (page.php)テンプレートのget_template_part()の第1パラメータは「content」、第2パラメータは「page」なので、「content-page.php」が呼び出されることになります。
4.コメントの出力
赤色のcomments_template()でコメントを出力します。
<div id="primary">
<div id="content" role="main">
<?php the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php comments_template( '', true ); ?>
</div><!-- #content -->
</div><!-- #primary -->
コメントは次の赤枠部分が該当します(冒頭のスクリーンショットはディスカッションの設定で非表示にしています)。
comments_template()はコメントテンプレートを取得する関数で、wp-includes/comment-template.phpに実装されています(長いので掲載は割愛)。
パラメータの意味は次のとおりです。
- 第1パラメータ:コメントテンプレート名を指定。値が空の場合は「comments.php」を取得
- 第2パラメータ:コメント分割の要否。ここでは「true」が設定されているのでコメントを分割表示
5.フッター情報の出力
フッター情報は赤枠部分が対応します。
フッター情報はget_footer()で出力します。
<?php get_footer(); ?>
get_footer()は、wp-includes/general-template.phpに実装されています。
wp-includes/general-template.php
function get_footer( $name = null ) {
do_action( 'get_footer', $name );
$templates = array();
if ( isset($name) )
$templates[] = "footer-{$name}.php";
$templates[] = 'footer.php';
// Backward compat code will be removed in a future release
if ('' == locate_template($templates, true))
load_template( ABSPATH . WPINC . '/theme-compat/footer.php');
}
WordPressテーマ(テンプレート)バージョンアップ
当ブログで配布中のWordPressテーマをバージョンアップしました。最新バージョンは3.0.20です。
![]()
1.変更点
まず、サイドバーのコメント・トラックバック一覧表示用の「Commented entry listプラグイン」の機能をテーマに同梱しました。これで、「Commented entry listプラグイン」をインストールしなくてもすむようにしました。
コメント・トラックバック一覧

次に、カテゴリーアーカイブのパンくずリスト表示で一部不具合があったため、これを対処しました。
カテゴリーアーカイブのパンくずリスト

スタイルも一部変更し、中央カラムのコンテンツのフォントサイズを大きくしています。その他、バージョン3以降で非推奨となったテンプレートタグを推奨テンプレートタグに書き換えました。
2.ダウンロード
バージョンアップしたテーマは以下のエントリーからダウンロードできます。
WordPressのTwenty Elevenテーマ解説:content.php(その2)
WordPressの勉強も兼ねて、Twenty Elevenテーマの各テンプレートについて解説してみたいと思います。確認バージョンは3.2.1です。
今回は「WordPressのTwenty Elevenテーマ解説:content.php:その1」の続きです。
content.php:その2
Twenty Elevenテーマの「content.php」で出力される内容は次の赤枠部分になります。スクリーンショットはメインページです。
テンプレートのソースコードは次のとおりです。この回で説明するのは青色で示す部分です。
<?php
/**
* The default template for displaying content
*
* @package WordPress
* @subpackage Twenty_Eleven
* @since Twenty Eleven 1.0
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php if ( is_sticky() ) : ?>
<hgroup>
<h2 class="entry-title"><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyeleven' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<h3 class="entry-format"><?php _e( 'Featured', 'twentyeleven' ); ?></h3>
</hgroup>
<?php else : ?>
<h1 class="entry-title"><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyeleven' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h1>
<?php endif; ?>
<?php if ( 'post' == get_post_type() ) : ?>
<div class="entry-meta">
<?php twentyeleven_posted_on(); ?>
</div><!-- .entry-meta -->
<?php endif; ?>
<?php if ( comments_open() && ! post_password_required() ) : ?>
<div class="comments-link">
<?php comments_popup_link( '<span class="leave-reply">' . __( 'Reply', 'twentyeleven' ) . '</span>', _x( '1', 'comments number', 'twentyeleven' ), _x( '%', 'comments number', 'twentyeleven' ) ); ?>
</div>
<?php endif; ?>
</header><!-- .entry-header -->
<?php if ( is_search() ) : // Only display Excerpts for Search ?>
<div class="entry-summary">
<?php the_excerpt(); ?>
</div><!-- .entry-summary -->
<?php else : ?>
<div class="entry-content">
<?php the_content( __( 'Continue reading <span class="meta-nav">→</span>', 'twentyeleven' ) ); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'twentyeleven' ) . '</span>', 'after' => '</div>' ) ); ?>
</div><!-- .entry-content -->
<?php endif; ?>
<footer class="entry-meta">
<?php $show_sep = false; ?>
<?php if ( 'post' == get_post_type() ) : // Hide category and tag text for pages on Search ?>
<?php
/* translators: used between list items, there is a space after the comma */
$categories_list = get_the_category_list( __( ', ', 'twentyeleven' ) );
if ( $categories_list ):
?>
<span class="cat-links">
<?php printf( __( '<span class="%1$s">Posted in</span> %2$s', 'twentyeleven' ), 'entry-utility-prep entry-utility-prep-cat-links', $categories_list );
$show_sep = true; ?>
</span>
<?php endif; // End if categories ?>
<?php
/* translators: used between list items, there is a space after the comma */
$tags_list = get_the_tag_list( '', __( ', ', 'twentyeleven' ) );
if ( $tags_list ):
if ( $show_sep ) : ?>
<span class="sep"> | </span>
<?php endif; // End if $show_sep ?>
<span class="tag-links">
<?php printf( __( '<span class="%1$s">Tagged</span> %2$s', 'twentyeleven' ), 'entry-utility-prep entry-utility-prep-tag-links', $tags_list );
$show_sep = true; ?>
</span>
<?php endif; // End if $tags_list ?>
<?php endif; // End if 'post' == get_post_type() ?>
<?php if ( comments_open() ) : ?>
<?php if ( $show_sep ) : ?>
<span class="sep"> | </span>
<?php endif; // End if $show_sep ?>
<span class="comments-link"><?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a reply', 'twentyeleven' ) . '</span>', __( '<b>1</b> Reply', 'twentyeleven' ), __( '<b>%</b> Replies', 'twentyeleven' ) ); ?></span>
<?php endif; // End if comments_open() ?>
<?php edit_post_link( __( 'Edit', 'twentyeleven' ), '<span class="edit-link">', '</span>' ); ?>
</footer><!-- #entry-meta -->
</article><!-- #post-<?php the_ID(); ?> -->
1.本文の出力
次の部分で本文を出力します。
<?php if ( is_search() ) : // Only display Excerpts for Search ?>
<div class="entry-summary">
<?php the_excerpt(); ?>
</div><!-- .entry-summary -->
<?php else : ?>
<div class="entry-content">
<?php the_content( __( 'Continue reading <span class="meta-nav">→</span>', 'twentyeleven' ) ); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'twentyeleven' ) . '</span>', 'after' => '</div>' ) ); ?>
</div><!-- .entry-content -->
<?php endif; ?>
is_search()は検索結果ページであることをチェックする関数で、wp-includes/query.phpに実装されています。
function is_search() {
global $wp_query;
if ( ! isset( $wp_query ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
return false;
}
return $wp_query->is_search();
}
検索結果ページの場合は、以下の部分を実行します。
<div class="entry-summary">
<?php the_excerpt(); ?>
</div><!-- .entry-summary -->
赤色のthe_excerpt()は抜粋を出力する関数で、wp-includes/post-template.phpに実装されています。パラメータはありません。
function the_excerpt() {
echo apply_filters('the_excerpt', get_the_excerpt());
}
検索結果ページの場合は投稿画面の「抜粋」に記載された内容を出力します。抜粋に入力がない場合は最大110文字までを三点リーダーつきで出力します。日本語版の場合は出力文字数をWP Multibyte Patchプラグインで制御しています。
検索結果ページ以外の場合は、以下の部分を実行します。
<div class="entry-content">
<?php the_content( __( 'Continue reading <span class="meta-nav">→</span>', 'twentyeleven' ) ); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'twentyeleven' ) . '</span>', 'after' => '</div>' ) ); ?>
</div><!-- .entry-content -->
赤色のthe_content()は本文を出力する関数で、wp-includes/post-template.phpに実装されています。
function the_content($more_link_text = null, $stripteaser = 0) {
$content = get_the_content($more_link_text, $stripteaser);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content;
}
同じく赤色のwp_link_pages()は、分割された投稿でページリンクを表示する関数で、wp-includes/post-template.phpに実装されています。記事本文に記述した以下のHTMLコメントで記事をページ分割します。
<!--nextpage-->
分割すると次のようなリンクが表示されます。
サンプル

2.カテゴリーの出力
以下の部分でカテゴリーを出力します。
<footer class="entry-meta">
<?php $show_sep = false; ?>
<?php if ( 'post' == get_post_type() ) : // Hide category and tag text for pages on Search ?>
<?php
/* translators: used between list items, there is a space after the comma */
$categories_list = get_the_category_list( __( ', ', 'twentyeleven' ) );
if ( $categories_list ):
?>
<span class="cat-links">
<?php printf( __( '<span class="%1$s">Posted in</span> %2$s', 'twentyeleven' ), 'entry-utility-prep entry-utility-prep-cat-links', $categories_list );
$show_sep = true; ?>
</span>
<?php endif; // End if categories ?>
サンプル

赤色のget_the_category_list()はカテゴリー一覧を取得する関数で、wp-includes/category-template.phpに実装されています。ここではパラメータは設定されていませんが、次のパラメータが設定可能です。
- 第1パラメータ:区切り文字
- 第2パラメータ:親カテゴリの表示とリンク方法。「multiple」「single」を指定可能(詳細は後述)。パラメータなしの場合は親カテゴリーを表示しない
- 第3パラメータ:記事ID。省略時は処理中の記事IDを適用
第2パラメータで「multiple」を指定すると、次のように親カテゴリ・子カテゴリのリンクが独立します。

「single」を指定すると、次のように親カテゴリは表示されますがリンクは子カテゴリのみになります。

3.タグの出力
以下の部分でタグを出力します。
<?php
/* translators: used between list items, there is a space after the comma */
$tags_list = get_the_tag_list( '', __( ', ', 'twentyeleven' ) );
if ( $tags_list ):
if ( $show_sep ) : ?>
<span class="sep"> | </span>
<?php endif; // End if $show_sep ?>
<span class="tag-links">
<?php printf( __( '<span class="%1$s">Tagged</span> %2$s', 'twentyeleven' ), 'entry-utility-prep entry-utility-prep-tag-links', $tags_list );
$show_sep = true; ?>
</span>
<?php endif; // End if $tags_list ?>
<?php endif; // End if 'post' == get_post_type() ?>
サンプル
![]()
赤色のget_the_tag_list()はタグ一覧を取得する関数で、カテゴリーと同様、wp-includes/category-template.phpに実装されています。ここではパラメータは設定されていませんが、次のパラメータが設定可能です。
- 第1パラメータ:リストの最初に出力する文字列
- 第2パラメータ:区切り文字
- 第3パラメータ:リストの最後に出力する文字列
変数$show_sepは、カテゴリとタグの間のセパレータの表示・非表示を判定するためのものです。カテゴリ表示なし・タグ表示ありの場合はセパレータを表示しません。
4.コメントリンクの出力
以下の部分でコメントリンクを出力します。
<?php if ( comments_open() ) : ?>
<?php if ( $show_sep ) : ?>
<span class="sep"> | </span>
<?php endif; // End if $show_sep ?>
<span class="comments-link"><?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a reply', 'twentyeleven' ) . '</span>', __( '<b>1</b> Reply', 'twentyeleven' ), __( '<b>%</b> Replies', 'twentyeleven' ) ); ?></span>
<?php endif; // End if comments_open() ?>
<?php edit_post_link( __( 'Edit', 'twentyeleven' ), '<span class="edit-link">', '</span>' ); ?>
</footer><!-- #entry-meta -->
comments_open()は「その1」で解説したので省略します。
赤色のcomments_popup_link()はコメント投稿フォームへのリンクを出力する関数で、wp-includes/comment-template.phpに実装されています。パラメータの意味は次のとおりです。
- 第1パラメータ:コメントがない場合の表示
- 第2パラメータ:コメントが1件の場合の表示
- 第3パラメータ:コメントが2件以上の場合の表示
- 第4パラメータ:a要素のclass属性値
- 第5パラメータ:コメントが動作していない場合
関数名の通りポップアップも可能です。次の内容をhead要素に設定しておけば、ポップアップコメントになります。
<?php comments_popup_script(); ?>
サンプル

同じく赤色のedit_post_link()は、記事やページの編集画面へのリンクを出力する関数で、wp-includes/link-template.phpに実装されています。
function edit_post_link( $link = null, $before = '', $after = '', $id = 0 ) {
if ( !$post = &get_post( $id ) )
return;
if ( !$url = get_edit_post_link( $post->ID ) )
return;
if ( null === $link )
$link = __('Edit This');
$post_type_obj = get_post_type_object( $post->post_type );
$link = '<a class="post-edit-link" href="' . $url . '" title="' . esc_attr( $post_type_obj->labels->edit_item ) . '">' . $link . '</a>';
echo $before . apply_filters( 'edit_post_link', $link, $post->ID ) . $after;
}
サンプル

edit_post_link()には、次のパラメータが設定可能です。
- 第1パラメータ:リンク名
- 第2パラメータ:リンクの前に出力する文字列
- 第3パラメータ:リンクの後に出力する文字列
WordPressのTwenty Elevenテーマ解説:content.php(その1)
WordPressの勉強も兼ねて、Twenty Elevenテーマの各テンプレートについて解説してみたいと思います。確認バージョンは3.2.1です。
content.php:その1
Twenty Elevenテーマの「content.php」で出力される内容は次の赤枠部分になります。スクリーンショットはメインページです。
テンプレートのソースコードは次のとおりです。この回で説明するのは青色で示す部分です。
<?php
/**
* The default template for displaying content
*
* @package WordPress
* @subpackage Twenty_Eleven
* @since Twenty Eleven 1.0
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php if ( is_sticky() ) : ?>
<hgroup>
<h2 class="entry-title"><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyeleven' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<h3 class="entry-format"><?php _e( 'Featured', 'twentyeleven' ); ?></h3>
</hgroup>
<?php else : ?>
<h1 class="entry-title"><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyeleven' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h1>
<?php endif; ?>
<?php if ( 'post' == get_post_type() ) : ?>
<div class="entry-meta">
<?php twentyeleven_posted_on(); ?>
</div><!-- .entry-meta -->
<?php endif; ?>
<?php if ( comments_open() && ! post_password_required() ) : ?>
<div class="comments-link">
<?php comments_popup_link( '<span class="leave-reply">' . __( 'Reply', 'twentyeleven' ) . '</span>', _x( '1', 'comments number', 'twentyeleven' ), _x( '%', 'comments number', 'twentyeleven' ) ); ?>
</div>
<?php endif; ?>
</header><!-- .entry-header -->
<?php if ( is_search() ) : // Only display Excerpts for Search ?>
<div class="entry-summary">
<?php the_excerpt(); ?>
</div><!-- .entry-summary -->
<?php else : ?>
<div class="entry-content">
<?php the_content( __( 'Continue reading <span class="meta-nav">→</span>', 'twentyeleven' ) ); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'twentyeleven' ) . '</span>', 'after' => '</div>' ) ); ?>
</div><!-- .entry-content -->
<?php endif; ?>
<footer class="entry-meta">
<?php $show_sep = false; ?>
<?php if ( 'post' == get_post_type() ) : // Hide category and tag text for pages on Search ?>
<?php
/* translators: used between list items, there is a space after the comma */
$categories_list = get_the_category_list( __( ', ', 'twentyeleven' ) );
if ( $categories_list ):
?>
<span class="cat-links">
<?php printf( __( '<span class="%1$s">Posted in</span> %2$s', 'twentyeleven' ), 'entry-utility-prep entry-utility-prep-cat-links', $categories_list );
$show_sep = true; ?>
</span>
<?php endif; // End if categories ?>
<?php
/* translators: used between list items, there is a space after the comma */
$tags_list = get_the_tag_list( '', __( ', ', 'twentyeleven' ) );
if ( $tags_list ):
if ( $show_sep ) : ?>
<span class="sep"> | </span>
<?php endif; // End if $show_sep ?>
<span class="tag-links">
<?php printf( __( '<span class="%1$s">Tagged</span> %2$s', 'twentyeleven' ), 'entry-utility-prep entry-utility-prep-tag-links', $tags_list );
$show_sep = true; ?>
</span>
<?php endif; // End if $tags_list ?>
<?php endif; // End if 'post' == get_post_type() ?>
<?php if ( comments_open() ) : ?>
<?php if ( $show_sep ) : ?>
<span class="sep"> | </span>
<?php endif; // End if $show_sep ?>
<span class="comments-link"><?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a reply', 'twentyeleven' ) . '</span>', __( '<b>1</b> Reply', 'twentyeleven' ), __( '<b>%</b> Replies', 'twentyeleven' ) ); ?></span>
<?php endif; // End if comments_open() ?>
<?php edit_post_link( __( 'Edit', 'twentyeleven' ), '<span class="edit-link">', '</span>' ); ?>
</footer><!-- #entry-meta -->
</article><!-- #post-<?php the_ID(); ?> -->
1.article要素の出力
次の部分でarticle要素のid属性とclass属性を出力します。
<?php
…中略…
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
the_ID()は、記事IDを出力する関数で、wp-includes/post-template.phpに実装されています。パラメータはありません。
wp-includes/post-template.php
function the_ID() {
echo get_the_ID();
}
the_ID()の中で起動されているget_the_ID()は記事データのIDを返却する関数で、同じファイルに実装されています。
function get_the_ID() {
global $post;
return $post->ID;
}
post_class()は、記事の状態に応じたclass属性およびclass属性値を出力する関数で、同じファイルに実装されています。
function post_class( $class = '', $post_id = null ) {
// Separates classes with a single space, collates classes for post DIV
echo 'class="' . join( ' ', get_post_class( $class, $post_id ) ) . '"';
}
post_class()の中で起動されているget_post_class()は同じファイルに実装されていて(長いので掲載は割愛します)、この関数でclass属性値を設定しています。たとえばstickyであれば「sticky」というclass属性値を追加します。「hentry」は常に設定されます。
the_ID()とpost_class()で次のようなマークアップを出力します。
<article id="post-6" class="post-6 post type-post status-publish format-standard hentry category-1">
2.header要素の出力
次の部分でheader要素を出力します。
<header class="entry-header">
<?php if ( is_sticky() ) : ?>
<hgroup>
<h2 class="entry-title"><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyeleven' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<h3 class="entry-format"><?php _e( 'Featured', 'twentyeleven' ); ?></h3>
</hgroup>
<?php else : ?>
<h1 class="entry-title"><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyeleven' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h1>
<?php endif; ?>
フロントページに固定されているページは次のようなマークアップを出力します。「注目」が表示され、投稿年月日が非表示になります。
<hgroup>
<h2 class="entry-title"><a href="http://user-domain/?p=1" title="モバイルサイトオープン へのパーマリンク" rel="bookmark">モバイルサイトオープン</a></h2>
<h3 class="entry-format">注目</h3>
</hgroup>
サンプル(フロントページに固定)

それ以外のページでは次のようなマークアップを出力します。
<h1 class="entry-title"><a href="http://user-domain/?p=1" title="モバイルサイトオープン へのパーマリンク" rel="bookmark">モバイルサイトオープン</a></h1>
サンプル(フロントページに固定していない)

is_sticky()は、現在の投稿について「この投稿を先頭に固定表示」チェックボックスがチェックされているかどうかを判定する関数で、wp-includes/post.phpに実装されています。
wp-includes/post.php
function is_sticky( $post_id = 0 ) {
$post_id = absint( $post_id );
if ( ! $post_id )
$post_id = get_the_ID();
$stickies = get_option( 'sticky_posts' );
if ( ! is_array( $stickies ) )
return false;
if ( in_array( $post_id, $stickies ) )
return true;
return false;
}
「この投稿を先頭に固定表示」は投稿画面の「公開状態」の「この投稿を先頭に固定表示」を選択していると有効になります。

the_permalink()は記事のパーマリンクを出力する関数で、wp-includes/link-template.phpに実装されています。パラメータはありません。
wp-includes/link-template.php
function the_permalink() {
echo apply_filters('the_permalink', get_permalink());
}
the_title_attribute()は、記事タイトルを属性値用に出力する関数で、wp-includes/post-template.phpに実装されています。タグ(<~>)は除去され、&は実体参照されます。パラメータのechoが0またはfalseであれば値を返却し、1またはtrueであれば出力します。
wp-includes/post-template.php
function the_title_attribute( $args = '' ) {
$title = get_the_title();
if ( strlen($title) == 0 )
return;
$defaults = array('before' => '', 'after' => '', 'echo' => true);
$r = wp_parse_args($args, $defaults);
extract( $r, EXTR_SKIP );
$title = $before . $title . $after;
$title = esc_attr(strip_tags($title));
if ( $echo )
echo $title;
else
return $title;
}
esc_attr__()は、ローカライズに加えて値に含まれる「<>&"'」を実体参照して出力する関数で、wp-includes/l10n.phpに実装されています。
wp-includes/l10n.php
function esc_attr__( $text, $domain = 'default' ) {
return esc_attr( translate( $text, $domain ) );
}
まとめると、
<?php printf( esc_attr__( 'Permalink to %s', 'twentyeleven' ), the_title_attribute( 'echo=0' ) ); ?>
は、the_title_attribute()で記事タイトルを返却したものが%sに設定され、さらにesc_attr__()でローカライズと実体参照を行います。
3.投稿年月日の出力
次の部分で投稿タイプが「記事」の場合のみ、記事の投稿年月日を出力します。
<?php if ( 'post' == get_post_type() ) : ?>
<div class="entry-meta">
<?php twentyeleven_posted_on(); ?>
</div><!-- .entry-meta -->
<?php endif; ?>
投稿年月日のサンプル
![]()
get_post_type()は投稿タイプを取得する関数で、wp-includes/link-template.phpに実装されています。
wp-includes/link-template.php
function get_post_type_archive_link( $post_type ) {
global $wp_rewrite;
if ( ! $post_type_obj = get_post_type_object( $post_type ) )
return false;
if ( ! $post_type_obj->has_archive )
return false;
if ( get_option( 'permalink_structure' ) && is_array( $post_type_obj->rewrite ) ) {
$struct = ( true === $post_type_obj->has_archive ) ? $post_type_obj->rewrite['slug'] : $post_type_obj->has_archive;
if ( $post_type_obj->rewrite['with_front'] )
$struct = $wp_rewrite->front . $struct;
else
$struct = $wp_rewrite->root . $struct;
$link = home_url( user_trailingslashit( $struct, 'post_type_archive' ) );
} else {
$link = home_url( '?post_type=' . $post_type );
}
return apply_filters( 'post_type_archive_link', $link, $post_type );
}
この関数は次の値を返却します。
- post:記事
- page:固定ページ
- attachment:添付ファイル
- revision:投稿リビジョン
twentyeleven_posted_on()は、テーマのfunctions.phpに実装されている関数です。
functions.php
function twentyeleven_posted_on() {
printf( __( '<span class="sep">Posted on </span><a href="%1$s" title="%2$s" rel="bookmark"><time class="entry-date" datetime="%3$s" pubdate>%4$s</time></a><span class="by-author"> <span class="sep"> by </span> <span class="author vcard"><a class="url fn n" href="%5$s" title="%6$s" rel="author">%7$s</a></span></span>', 'twentyeleven' ),
esc_url( get_permalink() ),
esc_attr( get_the_time() ),
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date() ),
esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ),
sprintf( esc_attr__( 'View all posts by %s', 'twentyeleven' ), get_the_author() ),
esc_html( get_the_author() )
);
}
この関数では次のようなマークアップを出力します。
<div class="entry-meta">
<span class="sep">投稿日:</span>
<a href="https://user-domain/?p=1" title="1:17 AM" rel="bookmark">
<time class="entry-date" datetime="2011-10-14T01:17:30+00:00" pubdate>2011年10月14日</time>
</a>
<span class="by-author">
<span class="sep">作成者:</span>
<span class="author vcard">
<a class="url fn n" href="https://user-domain/?author=1" title="admin の投稿をすべて表示" rel="author">admin</a>
</span>
</span>
</div>
4.コメントリンクの出力
次の部分でコメントリンクを出力します。
<?php if ( comments_open() && ! post_password_required() ) : ?>
<div class="comments-link">
<?php comments_popup_link( '<span class="leave-reply">' . __( 'Reply', 'twentyeleven' ) . '</span>', _x( '1', 'comments number', 'twentyeleven' ), _x( '%', 'comments number', 'twentyeleven' ) ); ?>
</div>
<?php endif; ?>
コメントリンクはふきだしの形で、その中にコメント数を表示します。
コメントリンクのサンプル

comments_open()はコメント投稿が許可されていることをチェックする関数で、wp-includes/comment-template.phpに実装されています。
wp-includes/comment-template.php
function comments_open( $post_id=NULL ) {
$_post = get_post($post_id);
$open = ( 'open' == $_post->comment_status );
return apply_filters( 'comments_open', $open, $post_id );
}
投稿画面の「ディスカッション」の「コメントの投稿を許可する。」がチェックされていればcomments_open()でtrueを返却します。

post_password_required()はパスワード保護されていることをチェックする関数で、wp-includes/post-template.phpに実装されています。
wp-includes/post-template.php
function post_password_required( $post = null ) {
$post = get_post($post);
if ( empty($post->post_password) )
return false;
if ( !isset($_COOKIE['wp-postpass_' . COOKIEHASH]) )
return true;
if ( $_COOKIE['wp-postpass_' . COOKIEHASH] != $post->post_password )
return true;
return false;
}
パスワード保護は記事編集画面の「公開状態」の「パスワード保護」を選択してパスワードを設定すると有効になります。

_x()はコンテキストに応じた翻訳テキストを取得する関数で、wp-includes/l10n.phpに実装されています。
wp-includes/l10n.php
function _x( $text, $context, $domain = 'default' ) {
return translate_with_gettext_context( $text, $context, $domain );
}
ちなみにパスワード保護を行うと、記事本文が次のような表示に切り替わります。
WordPressのTwenty Elevenテーマ解説:単一記事の投稿 (single.php)
WordPressの勉強も兼ねて、Twenty Elevenテーマの各テンプレートについて解説しています。確認バージョンは3.2.1です。
単一記事の投稿 (single.php)
Twenty Elevenテーマの「単一記事の投稿 (single.php)」で出力されるページは次のように、記事のコンテンツとコメントなどが表示されます。
テンプレートのソースコードは次のとおりです。
<?php
/**
* The Template for displaying all single posts.
*
* @package WordPress
* @subpackage Twenty_Eleven
* @since Twenty Eleven 1.0
*/
get_header(); ?>
<div id="primary">
<div id="content" role="main">
<?php while ( have_posts() ) : the_post(); ?>
<nav id="nav-single">
<h3 class="assistive-text"><?php _e( 'Post navigation', 'twentyeleven' ); ?></h3>
<span class="nav-previous"><?php previous_post_link( '%link', __( '<span class="meta-nav">←</span> Previous', 'twentyeleven' ) ); ?></span>
<span class="nav-next"><?php next_post_link( '%link', __( 'Next <span class="meta-nav">→</span>', 'twentyeleven' ) ); ?></span>
</nav><!-- #nav-single -->
<?php get_template_part( 'content', 'single' ); ?>
<?php comments_template( '', true ); ?>
<?php endwhile; // end of the loop. ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_footer(); ?>
以下、順を追ってテンプレートの内容について解説します。「WordPressのTwenty Elevenテーマ解説:メインインデックスのテンプレート (index.php)」と一部重複している部分がありますが、この記事だけで一気に読みきれるよう、他の記事への参照は行ってません。
1.ヘッダー情報の出力
ヘッダー情報はget_header()で出力します。
<?php
…中略…
get_header(); ?>
ヘッダー情報は赤枠部分が対応します。
get_header()はwp-includes/general-template.phpに実装されています。
wp-includes/general-template.php
function get_header( $name = null ) {
do_action( 'get_header', $name );
$templates = array();
if ( isset($name) )
$templates[] = "header-{$name}.php";
$templates[] = 'header.php';
// Backward compat code will be removed in a future release
if ('' == locate_template($templates, true))
load_template( ABSPATH . WPINC . '/theme-compat/header.php');
}
do_action()はフックポイント「get_header」の作成を行っています。
do_action( 'get_header', $name );
プラグインを作成している方はすでにご存知と思いますが、add_action()を使えばフックポイントに任意のアクションを追加できます。
例えばプラグインで次のコードを記述すれば、フックポイント「get_header」、つまりdo_action('get_header')の実行時にfoo()が起動され、doctype宣言の前に「foo」が出力されます。
<?php
/*
Plugin Name: Foo
Description: Foo
Version: 1.0
*/
function foo() {
echo "foo";
}
add_action('get_header', 'foo');
?>
話を戻して、get_header()では、パラメータに設定した文字列をテンプレート名として利用します。「get_header('foo')」と書いておけば、「header-foo.php」を「header.php」の代わりにロードします。パラメータの設定がなければ「header.php」をロードします。
$templates = array();
if ( isset($name) )
$templates[] = "header-{$name}.php";
$templates[] = 'header.php';
2.記事データの取得
赤色で示したwhile文のhave_posts()とthe_post()で、記事データを取得します。
<?php while ( have_posts() ) : the_post(); ?>
<nav id="nav-single">
<h3 class="assistive-text"><?php _e( 'Post navigation', 'twentyeleven' ); ?></h3>
<span class="nav-previous"><?php previous_post_link( '%link', __( '<span class="meta-nav">←</span> Previous', 'twentyeleven' ) ); ?></span>
<span class="nav-next"><?php next_post_link( '%link', __( 'Next <span class="meta-nav">→</span>', 'twentyeleven' ) ); ?></span>
</nav><!-- #nav-single -->
<?php get_template_part( 'content', 'single' ); ?>
<?php comments_template( '', true ); ?>
<?php endwhile; // end of the loop. ?>
have_posts()は投稿記事をチェックする関数で、wp-includes/query.phpに実装されています。
wp-includes/query.php
function have_posts() {
global $wp_query;
return $wp_query->have_posts();
}
投稿記事が存在する場合はtrue、存在しない場合はfalseを返却します。パラメータはありません。ここではhave_posts()をwhile文で使っていますが、メインインデックスなどif文で使用している箇所もあります。
付け加えると、単一記事や固定記事ではwhile文を利用しなくても記事データを取得できます。よって次のような構造でも良いと思いますが、認識誤りがありましたらご指摘ください。
<?php if ( have_posts() ) : the_post(); ?>
…中略…
<?php endif; ?>
the_post()は投稿データをロードする関数で、wp-includes/query.phpに実装されています。the_post()を実行しただけでは何も出力しません。
wp-includes/query.php
function the_post() {
global $wp_query;
$wp_query->the_post();
}
3.前後記事のリンクの出力
赤色部分で前後記事のリンクを出力します。
<?php while ( have_posts() ) : the_post(); ?>
<nav id="nav-single">
<h3 class="assistive-text"><?php _e( 'Post navigation', 'twentyeleven' ); ?></h3>
<span class="nav-previous"><?php previous_post_link( '%link', __( '<span class="meta-nav">←</span> Previous', 'twentyeleven' ) ); ?></span>
<span class="nav-next"><?php next_post_link( '%link', __( 'Next <span class="meta-nav">→</span>', 'twentyeleven' ) ); ?></span>
</nav><!-- #nav-single -->
<?php get_template_part( 'content', 'single' ); ?>
<?php comments_template( '', true ); ?>
<?php endwhile; // end of the loop. ?>
前後記事のリンクは次の赤枠部分が該当します。
以下は(X)HTMLマークアップの出力例です。
<span class="nav-previous"><a href="http://user-domain/?p=1" rel="prev"><span class="meta-nav">←</span> 前へ</a></span>
<span class="nav-next"><a href="http://user-domain/?p=6" rel="next">次へ <span class="meta-nav">→</span></a></span>
previous_post_link()は前の記事のリンクを出力する関数、next_post_link()は次の記事のリンクを出力する関数で、いずれもwp-includes/link-template.phpに実装されています。
wp-includes/query.php
function previous_post_link($format='« %link', $link='%title', $in_same_cat = false, $excluded_categories = '') {
adjacent_post_link($format, $link, $in_same_cat, $excluded_categories, true);
}
function next_post_link($format='%link »', $link='%title', $in_same_cat = false, $excluded_categories = '') {
adjacent_post_link($format, $link, $in_same_cat, $excluded_categories, false);
}
パラメータの意味は次のとおりです。
- 第1パラメータ:リンクの文字列の書式。文字列に「%link」を設定すれば、その部分がa要素に置き換わります
- 第2パラメータ:リンクのテキストを指定。デフォルトは前(または次)の記事タイトル(%title)
- 第3パラメータ:同一カテゴリの前後記事だけの表示要否(ここではfalse)
- 第4パラメータ:除外したいカテゴリID(ここでは空)
処理の中で起動されているadjacent_post_link()で実際の処理を行っています。前記事・後記事の区別は第5パラメータで行っています。
function adjacent_post_link($format, $link, $in_same_cat = false, $excluded_categories = '', $previous = true) {
if ( $previous && is_attachment() )
$post = & get_post($GLOBALS['post']->post_parent);
else
$post = get_adjacent_post($in_same_cat, $excluded_categories, $previous);
if ( !$post )
return;
$title = $post->post_title;
if ( empty($post->post_title) )
$title = $previous ? __('Previous Post') : __('Next Post');
$title = apply_filters('the_title', $title, $post->ID);
$date = mysql2date(get_option('date_format'), $post->post_date);
$rel = $previous ? 'prev' : 'next';
$string = '<a href="'.get_permalink($post).'" rel="'.$rel.'">';
$link = str_replace('%title', $title, $link);
$link = str_replace('%date', $date, $link);
$link = $string . $link . '</a>';
$format = str_replace('%link', $link, $format);
$adjacent = $previous ? 'previous' : 'next';
echo apply_filters( "{$adjacent}_post_link", $format, $link );
}
5.コンテンツの出力
赤色のget_template_part()でコンテンツを出力します。
<?php while ( have_posts() ) : the_post(); ?>
<nav id="nav-single">
<h3 class="assistive-text"><?php _e( 'Post navigation', 'twentyeleven' ); ?></h3>
<span class="nav-previous"><?php previous_post_link( '%link', __( '<span class="meta-nav">←</span> Previous', 'twentyeleven' ) ); ?></span>
<span class="nav-next"><?php next_post_link( '%link', __( 'Next <span class="meta-nav">→</span>', 'twentyeleven' ) ); ?></span>
</nav><!-- #nav-single -->
<?php get_template_part( 'content', 'single' ); ?>
<?php comments_template( '', true ); ?>
<?php endwhile; // end of the loop. ?>
コンテンツは次の赤枠部分が該当します。
get_template_part()はwp-includes/general-template.phpに実装されています。
wp-includes/general-template.php
function get_template_part( $slug, $name = null ) {
do_action( "get_template_part_{$slug}", $slug, $name );
$templates = array();
if ( isset($name) )
$templates[] = "{$slug}-{$name}.php";
$templates[] = "{$slug}.php";
locate_template($templates, true, false);
}
do_action()でフックポイント「get_template_part_スラッグ名」の作成を行っています。この場合はスラッグ名は「content」なので、フックポイント名は「get_template_part_content」になります。
また、get_header()と同様、第1パラメータと第2パラメータに設定された名前を使ってテンプレートを呼び出します。第2パラメータが設定されていれば、「スラッグ名-名前.php」でテンプレートを呼び出します。第2パラメータが設定されていなければ、「スラッグ名.php」でテンプレートを呼び出します。
単一記事の投稿(single.php)テンプレートのget_template_part()の第1パラメータは「content」、第2パラメータは「single」なので、「content-single.php」が呼び出されることになります。
6.コメントの出力
赤色のcomments_template()でコメントを出力します。
<?php while ( have_posts() ) : the_post(); ?>
<nav id="nav-single">
<h3 class="assistive-text"><?php _e( 'Post navigation', 'twentyeleven' ); ?></h3>
<span class="nav-previous"><?php previous_post_link( '%link', __( '<span class="meta-nav">←</span> Previous', 'twentyeleven' ) ); ?></span>
<span class="nav-next"><?php next_post_link( '%link', __( 'Next <span class="meta-nav">→</span>', 'twentyeleven' ) ); ?></span>
</nav><!-- #nav-single -->
<?php get_template_part( 'content', 'single' ); ?>
<?php comments_template( '', true ); ?>
<?php endwhile; // end of the loop. ?>
コメントは次の赤枠部分が該当します。
comments_template()はコメントテンプレートを取得する関数で、wp-includes/comment-template.phpに実装されています(長いので掲載は割愛)。
パラメータの意味は次のとおりです。
- 第1パラメータ:コメントテンプレート名を指定。値が空の場合は「comments.php」を取得
- 第2パラメータ:コメント分割の要否。ここでは「true」が設定されているのでコメントを分割表示
なお、コメントの表示制御は管理画面の「設定」→「ディスカッション」で行います。
コメント表示の詳細については「コメント (comments.php)」テンプレートの解説で行います。
7.フッター情報の出力
フッター情報は赤枠部分が対応します。
フッター情報はget_footer()で出力します。
<?php get_footer(); ?>
get_footer()は、wp-includes/general-template.phpに実装されています。
wp-includes/general-template.php
function get_footer( $name = null ) {
do_action( 'get_footer', $name );
$templates = array();
if ( isset($name) )
$templates[] = "footer-{$name}.php";
$templates[] = 'footer.php';
// Backward compat code will be removed in a future release
if ('' == locate_template($templates, true))
load_template( ABSPATH . WPINC . '/theme-compat/footer.php');
}
WordPressのTwenty Elevenテーマ解説:フッター (footer.php)
WordPressの勉強も兼ねて、Twenty Elevenテーマの各テンプレートについて解説しています。確認バージョンは3.2.1です。
フッター (footer.php)
Twenty Elevenテーマの「フッター (footer.php)」は、スクリーンショットの赤枠で示す、WordPressのすべてのページのフッター部分(ヘッダーのdiv要素の終了タグ~</html>まで)に対応しています。
テンプレートのソースコードは次のとおりです。
<?php
/**
* The template for displaying the footer.
*
* Contains the closing of the id=main div and all content after
*
* @package WordPress
* @subpackage Twenty_Eleven
* @since Twenty Eleven 1.0
*/
?>
</div><!-- #main -->
<footer id="colophon" role="contentinfo">
<?php
/* A sidebar in the footer? Yep. You can can customize
* your footer with three columns of widgets.
*/
get_sidebar( 'footer' );
?>
<div id="site-generator">
<?php do_action( 'twentyeleven_credits' ); ?>
<a href="<?php echo esc_url( __( 'http://wordpress.org/', 'twentyeleven' ) ); ?>" title="<?php esc_attr_e( 'Semantic Personal Publishing Platform', 'twentyeleven' ); ?>" rel="generator"><?php printf( __( 'Proudly powered by %s', 'twentyeleven' ), 'WordPress' ); ?></a>
</div>
</footer><!-- #colophon -->
</div><!-- #page -->
<?php wp_footer(); ?>
</body>
</html>
1.フッターメニューの出力
デフォルトの状態では何も表示されていませんが、get_sidebar()でフッターの上部にメニューを追加できます。メニューを追加するには、管理画面の「外観」→「ウィジェット」の赤枠部分に任意のウィジェットをドラッグします。
下のスクリーンショットはフッターメニューを追加したところです。
get_sidebar()の役割は、テーマにある「sidebar.php」を取得することです。ここではパラメータに「footer」が設定されているので、「sidebar-footer.php」を取得します。
get_sidebar( 'footer' );
2.テーマクレジットの表示
フックポイント「twentyeleven_credits」でクレジットを表示することができます。
<?php do_action( 'twentyeleven_credits' ); ?>
デフォルトではこのフックポイントを利用している関数はありませんが、functions.phpに次のような関数を追加すれば「Twenty Eleven」というクレジットを表示します。
function add_twentyeleven_credits() {
echo 'Twenty Eleven';
}
add_action('twentyeleven_credits', 'add_twentyeleven_credits');
3.wp_footer()
wp_footer()は、テーマを作成するときに必ず必要なもので、通常はbody要素の終了タグの直前に記述します。wp_footer()を記述した部分に、プラグインで定義したスクリプトなどが出力されます。
wp_footer()は「wp_footer」フックポイントを実行するためだけの機能をもち、wp-includes/general-template.phpに実装されています。
function wp_footer() {
do_action('wp_footer');
}
プラグインなどでは次のように「wp_footer」フックポイントに登録します。この場合はscript要素を出力します。
<?php
/*
Plugin Name: add_script
Description: add_script
Version: 1.0
*/
function add_script() {
echo '<script type="text/javascript">// ... </script>';
}
add_action('wp_footer', 'add_script');
?>
「wp_footer」フックポイントにはデフォルトで2つの関数が登録されています。ひとつはwp_print_footer_scripts()です。
wp-includes/default-filters.php
add_action( 'wp_footer', 'wp_print_footer_scripts' );
wp_print_footer_scripts()は、スクリプトを出力する関数のようです。wp-includes/script-loader.phpに実装されています。
function wp_print_footer_scripts() {
return print_footer_scripts();
}
管理者でログインしている場合は次の1行が出力されます。これは次項で説明する「管理バー」用のスクリプトです。
<script type='text/javascript' src='http://user-domain/wp/wp-includes/js/admin-bar.js?ver=20110131'></script>
4.管理バーの出力
もうひとつはwp_admin_bar_render()で、これはページ上部に表示される管理バーを出力するためのものです。3項で説明したadmin-bar.jsも関係しています。
wp-includes/admin-bar.php
add_action( 'wp_footer', 'wp_admin_bar_render', 1000 );
管理バー

次のようなマークアップを出力します。
<div id="wpadminbar">
<div class="quicklinks">
<ul>
<li id="wp-admin-bar-my-account-with-avatar" class="menupop"><a href="http://user-domain/wp/wp-admin/profile.php"><span><img alt='' src='http://0.gravatar.com/avatar/ef7e5083fd46c3e1959a22621bc624c1?s=16&d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D16&r=G' class='avatar avatar-16 photo' height='16' width='16' />admin</span></a>
<ul>
<li id="wp-admin-bar-edit-profile" class=""><a href="http://user-domain/wp/wp-admin/profile.php">プロフィールを編集</a></li>
<li id="wp-admin-bar-logout" class=""><a href="http://user-domain/wp/wp-login.php?action=logout&_wpnonce=9dc934d1db">ログアウト</a></li>
</ul>
</li>
<li id="wp-admin-bar-dashboard" class=""><a href="http://user-domain/wp/wp-admin/">ダッシュボード</a></li>
<li id="wp-admin-bar-new-content" class="menupop"><a href="http://user-domain/wp/wp-admin/post-new.php?post_type=post"><span>新規追加</span></a>
<ul>
<li id="wp-admin-bar-new-post" class=""><a href="http://user-domain/wp/wp-admin/post-new.php?post_type=post">投稿</a></li>
<li id="wp-admin-bar-new-page" class=""><a href="http://user-domain/wp/wp-admin/post-new.php?post_type=page">固定ページ</a></li>
<li id="wp-admin-bar-new-media" class=""><a href="http://user-domain/wp/wp-admin/media-new.php">メディア</a></li>
<li id="wp-admin-bar-new-link" class=""><a href="http://user-domain/wp/wp-admin/link-add.php">リンク</a></li>
<li id="wp-admin-bar-new-user" class=""><a href="http://user-domain/wp/wp-admin/user-new.php">ユーザー</a></li>
<li id="wp-admin-bar-new-theme" class=""><a href="http://user-domain/wp/wp-admin/theme-install.php">テーマ</a></li>
<li id="wp-admin-bar-new-plugin" class=""><a href="http://user-domain/wp/wp-admin/plugin-install.php">プラグイン</a></li>
</ul>
</li>
<li id="wp-admin-bar-comments" class=""><a href="http://user-domain/wp/wp-admin/edit-comments.php">コメント </a></li>
<li id="wp-admin-bar-appearance" class="menupop"><a href="http://user-domain/wp/wp-admin/themes.php"><span>外観</span></a>
<ul>
<li id="wp-admin-bar-themes" class=""><a href="http://user-domain/wp/wp-admin/themes.php">テーマ</a></li>
<li id="wp-admin-bar-widgets" class=""><a href="http://user-domain/wp/wp-admin/widgets.php">ウィジェット</a></li>
<li id="wp-admin-bar-menus" class=""><a href="http://user-domain/wp/wp-admin/nav-menus.php">メニュー</a></li>
<li id="wp-admin-bar-background" class=""><a href="http://user-domain/wp/wp-admin/themes.php?page=custom-background">背景</a></li>
<li id="wp-admin-bar-header" class=""><a href="http://user-domain/wp/wp-admin/themes.php?page=custom-header">ヘッダー</a></li>
</ul>
</li>
</ul>
</div>
<div id="adminbarsearch-wrap">
<form action="http://user-domain/wp" method="get" id="adminbarsearch">
<input class="adminbar-input" name="s" id="adminbar-search" type="text" value="" maxlength="150" />
<input type="submit" class="adminbar-button" value="検索"/>
</form>
</div>
</div>
管理バーの表示・非表示はプロフィールのページで制御できます。

WordPressのTwenty Elevenテーマ解説:ヘッダー (header.php):その3
WordPressの勉強も兼ねて、Twenty Elevenテーマの各テンプレートについて解説しています。確認バージョンは3.2.1です。
今回は「WordPressのTwenty Elevenテーマ解説:ヘッダー (header.php):その2」の続きです。
ヘッダー (header.php):その3
Twenty Elevenテーマの「ヘッダー (header.php)」は、スクリーンショットの赤枠で示す、WordPressのすべてのページのヘッダー部分(DOCTYPE~<div id="main">まで)に対応しています。
テンプレートのソースコードは次のとおりです。この回で説明するのは青色で示す部分です。
<?php
/**
* The Header for our theme.
*
* Displays all of the <head> section and everything up till <div id="main">
*
* @package WordPress
* @subpackage Twenty_Eleven
* @since Twenty Eleven 1.0
*/
?><!DOCTYPE html>
<!--[if IE 6]>
<html id="ie6" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 7]>
<html id="ie7" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 8]>
<html id="ie8" <?php language_attributes(); ?>>
<![endif]-->
<!--[if !(IE 6) | !(IE 7) | !(IE 8) ]><!-->
<html <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width" />
<title><?php
/*
* Print the <title> tag based on what is being viewed.
*/
global $page, $paged;
wp_title( '|', true, 'right' );
// Add the blog name.
bloginfo( 'name' );
// Add the blog description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
echo " | $site_description";
// Add a page number if necessary:
if ( $paged >= 2 || $page >= 2 )
echo ' | ' . sprintf( __( 'Page %s', 'twentyeleven' ), max( $paged, $page ) );
?></title>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script>
<![endif]-->
<?php
/* We add some JavaScript to pages with the comment form
* to support sites with threaded comments (when in use).
*/
if ( is_singular() && get_option( 'thread_comments' ) )
wp_enqueue_script( 'comment-reply' );
/* Always have wp_head() just before the closing </head>
* tag of your theme, or you will break many plugins, which
* generally use this hook to add elements to <head> such
* as styles, scripts, and meta tags.
*/
wp_head();
?>
</head>
<body <?php body_class(); ?>>
<div id="page" class="hfeed">
<header id="branding" role="banner">
<hgroup>
<h1 id="site-title"><span><a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></span></h1>
<h2 id="site-description"><?php bloginfo( 'description' ); ?></h2>
</hgroup>
<?php
// Check to see if the header image has been removed
$header_image = get_header_image();
if ( ! empty( $header_image ) ) :
?>
<a href="<?php echo esc_url( home_url( '/' ) ); ?>">
<?php
// The header image
// Check if this is a post or page, if it has a thumbnail, and if it's a big one
if ( is_singular() &&
has_post_thumbnail( $post->ID ) &&
( /* $src, $width, $height */ $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), array( HEADER_IMAGE_WIDTH, HEADER_IMAGE_WIDTH ) ) ) &&
$image[1] >= HEADER_IMAGE_WIDTH ) :
// Houston, we have a new header image!
echo get_the_post_thumbnail( $post->ID, 'post-thumbnail' );
else : ?>
<img src="<?php header_image(); ?>" width="<?php echo HEADER_IMAGE_WIDTH; ?>" height="<?php echo HEADER_IMAGE_HEIGHT; ?>" alt="" />
<?php endif; // end check for featured image or standard header ?>
</a>
<?php endif; // end check for removed header image ?>
<?php
// Has the text been hidden?
if ( 'blank' == get_header_textcolor() ) :
?>
<div class="only-search<?php if ( ! empty( $header_image ) ) : ?> with-image<?php endif; ?>">
<?php get_search_form(); ?>
</div>
<?php
else :
?>
<?php get_search_form(); ?>
<?php endif; ?>
<nav id="access" role="navigation">
<h3 class="assistive-text"><?php _e( 'Main menu', 'twentyeleven' ); ?></h3>
<?php /* Allow screen readers / text browsers to skip the navigation menu and get right to the good stuff. */ ?>
<div class="skip-link"><a class="assistive-text" href="#content" title="<?php esc_attr_e( 'Skip to primary content', 'twentyeleven' ); ?>"><?php _e( 'Skip to primary content', 'twentyeleven' ); ?></a></div>
<div class="skip-link"><a class="assistive-text" href="#secondary" title="<?php esc_attr_e( 'Skip to secondary content', 'twentyeleven' ); ?>"><?php _e( 'Skip to secondary content', 'twentyeleven' ); ?></a></div>
<?php /* Our navigation menu. If one isn't filled out, wp_nav_menu falls back to wp_page_menu. The menu assiged to the primary position is the one used. If none is assigned, the menu with the lowest ID is used. */ ?>
<?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?>
</nav><!-- #access -->
</header><!-- #branding -->
<div id="main">
1.body要素のclass属性値の出力
body_class()でbody要素のclass属性を設定します。
<body <?php body_class(); ?>>
メインページでは次のような出力になります。
<body class="home blog single-author two-column right-sidebar">
記事ページでは次のような出力になります。
<body class="single single-post postid-6 single-format-gallery logged-in admin-bar single-author singular two-column right-sidebar">
body_class()はwp-includes/post-template.phpに実装されています。
wp-includes/post-template.php
function body_class( $class = '' ) {
// Separates classes with a single space, collates classes for body element
echo 'class="' . join( ' ', get_body_class( $class ) ) . '"';
}
中で起動されているget_body_class()も同じファイルに実装されています(長いので掲載は割愛)。
2.ブログタイトルとキャッチフレーズの出力

次の部分でブログタイトルとキャッチフレーズを出力します。
<hgroup>
<h1 id="site-title"><span><a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></span></h1>
<h2 id="site-description"><?php bloginfo( 'description' ); ?></h2>
</hgroup>
esc_url()でラップされているhome_url()は、wp-includes/link-template.phpに実装されています。
wp-includes/link-template.php
function home_url( $path = '', $scheme = null ) {
return get_home_url(null, $path, $scheme);
}
中で起動されているget_home_url()も同じファイルに実装されていて、中ではget_option()またはget_blog_option()の値を利用しています。プロトコル(http/https)は、is_ssl()とis_admin()で決定しています。is_ssl()はセキュアなアクセスである場合に実行し、プロトコル(http/https)を振り分けます。
function get_home_url( $blog_id = null, $path = '', $scheme = null ) {
$orig_scheme = $scheme;
if ( !in_array( $scheme, array( 'http', 'https' ) ) )
$scheme = is_ssl() && !is_admin() ? 'https' : 'http';
if ( empty( $blog_id ) || !is_multisite() )
$url = get_option( 'home' );
else
$url = get_blog_option( $blog_id, 'home' );
if ( 'http' != $scheme )
$url = str_replace( 'http://', "$scheme://", $url );
if ( !empty( $path ) && is_string( $path ) && strpos( $path, '..' ) === false )
$url .= '/' . ltrim( $path, '/' );
return apply_filters( 'home_url', $url, $path, $orig_scheme, $blog_id );
}
esc_url()はURLに含まれる文字列をURIエンコードする役割があり、wp-includes/formatting.phpに実装されています。esc_attr()は属性値として設定する文字列をエスケープする役割があり、同じファイルに実装されています。
get_bloginfo( 'name', 'display' ) )でブログ名をa要素のtitle属性に設定します。 bloginfo( 'name' )はブログ名、bloginfo( 'description' )はキャッチフレーズを出力します。get_bloginfo()とbloginfo()は既出のため、解説は省略します。
3.ヘッダ画像の出力
以下の部分でヘッダ画像を出力します。記事ページではアイキャッチ画像を表示することもできます。アイキャッチ画像の詳細については別途エントリーしたいと思います。
<?php
// Check to see if the header image has been removed
$header_image = get_header_image();
if ( ! empty( $header_image ) ) :
?>
<a href="<?php echo esc_url( home_url( '/' ) ); ?>">
<?php
// The header image
// Check if this is a post or page, if it has a thumbnail, and if it's a big one
if ( is_singular() &&
has_post_thumbnail( $post->ID ) &&
( /* $src, $width, $height */ $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), array( HEADER_IMAGE_WIDTH, HEADER_IMAGE_WIDTH ) ) ) &&
$image[1] >= HEADER_IMAGE_WIDTH ) :
// Houston, we have a new header image!
echo get_the_post_thumbnail( $post->ID, 'post-thumbnail' );
else : ?>
<img src="<?php header_image(); ?>" width="<?php echo HEADER_IMAGE_WIDTH; ?>" height="<?php echo HEADER_IMAGE_HEIGHT; ?>" alt="" />
<?php endif; // end check for featured image or standard header ?>
</a>
<?php endif; // end check for removed header image ?>
get_header_image()は画像のURLを収集する役割があり、変数$header_imageに次のようなURLを設定します。
http://user-domain/wp/wp-content/themes/twentyeleven/images/headers/trolley.jpg
get_header_image()はwp-includes/theme.phpに実装されています。
wp-includes/theme.php
function get_header_image() {
$default = defined( 'HEADER_IMAGE' ) ? HEADER_IMAGE : '';
$url = get_theme_mod( 'header_image', $default );
if ( 'remove-header' == $url )
return false;
if ( is_random_header_image() )
$url = get_random_header_image();
if ( is_ssl() )
$url = str_replace( 'http://', 'https://', $url );
else
$url = str_replace( 'https://', 'http://', $url );
return esc_url_raw( $url );
}
HEADER_IMAGEはテーマのfunctions.phpのtwentyeleven_setup()に定義されています(ただし値は空)。
function twentyeleven_setup() {
//...
define( 'HEADER_IMAGE', '' );
get_theme_mod()はテーマのオプションを取得する関数で、後述します。
remove-headerの判定は、「外観」→「ヘッダー」で「ヘッダー画像を削除」をクリックした場合に実行されるものと思われます(間違っていたらすいません)。

is_random_header_image()は同じ管理画面で「ランダム」を選択している場合に実行される関数で、wp-includes/theme.phpに実装されています。

return時のesc_url_raw()は、esc_url()をラップした関数で、wp-includes/formatting.phpに実装されています。
function esc_url_raw( $url, $protocols = null ) {
return esc_url( $url, $protocols, 'db' );
}
話を戻して、変数$header_imageに値が設定されていれば(=ヘッダ画像のURLがあれば)、home_url()とesc_url()を組み合わせて、ブログのメインページのリンクを出力します。
if ( ! empty( $header_image ) ) :
?>
<a href="<?php echo esc_url( home_url( '/' ) ); ?>">
// ...
</a>
<?php endif; // end check for removed header image ?>
リンクのコンテンツの出力部分は以下です。
<?php
// The header image
// Check if this is a post or page, if it has a thumbnail, and if it's a big one
if ( is_singular() &&
has_post_thumbnail( $post->ID ) &&
( /* $src, $width, $height */ $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), array( HEADER_IMAGE_WIDTH, HEADER_IMAGE_WIDTH ) ) ) &&
$image[1] >= HEADER_IMAGE_WIDTH ) :
// Houston, we have a new header image!
echo get_the_post_thumbnail( $post->ID, 'post-thumbnail' );
else : ?>
<img src="<?php header_image(); ?>" width="<?php echo HEADER_IMAGE_WIDTH; ?>" height="<?php echo HEADER_IMAGE_HEIGHT; ?>" alt="" />
<?php endif; // end check for featured image or standard header ?>
次の4つの条件を満たす場合、get_the_post_thumbnail()でアイキャッチ画像を出力します。
- 記事ページである(is_singular())
- 記事に画像が添付されている(post-thumbnail-template.php/has_post_thumbnail())
- 画像の情報(URL、高さ、幅)を取得できる
- 取得した画像の幅がHEADER_IMAGE_WIDTH(1000px)より大きい
get_the_post_thumbnail( $post->ID, 'post-thumbnail' );
上記以外の場合は、Twenty Elevenテーマで用意されている画像を表示します。
<img src="<?php header_image(); ?>" width="<?php echo HEADER_IMAGE_WIDTH; ?>" height="<?php echo HEADER_IMAGE_HEIGHT; ?>" alt="" />
header_image()はget_header_image()をechoする関数で、wp-includes/theme.phpに実装されています。
4.検索フォームの出力

次の部分で検索フォームを出力します。
<?php
// Has the text been hidden?
if ( 'blank' == get_header_textcolor() ) :
?>
<div class="only-search<?php if ( ! empty( $header_image ) ) : ?> with-image<?php endif; ?>">
<?php get_search_form(); ?>
</div>
<?php
else :
?>
<?php get_search_form(); ?>
<?php endif; ?>
デフォルトの状態ではページの右上に検索フォームを表示しますが、get_header_textcolor()の結果が「blank」であればdiv要素を挿入して、検索フォームをナビゲーションの右側に出力するようになっています。
get_header_textcolor()はHEADER_TEXTCOLORの値を出力する関数で、wp-includes/theme.phpに実装されています。
wp-includes/theme.php
function get_header_textcolor() {
$default = defined('HEADER_TEXTCOLOR') ? HEADER_TEXTCOLOR : '';
return get_theme_mod('header_textcolor', $default);
}
HEADER_TEXTCOLORは、テーマのfunctions.phpのtwentyeleven_setup()に定義されています。
function twentyeleven_setup() {
//...
define( 'HEADER_TEXTCOLOR', '000' );
twentyeleven_setup()は、functions.phpにある「after_setup_them」フックポイントで起動されます。
add_action( 'after_setup_theme', 'twentyeleven_setup' );
get_theme_mod()は、現在のテーマについて第1パラメータで指定したキーの値(modification value)を取得する関数のようです。キーと値はテーマを切り替えたときにwp_optionsテーブルに保存されるようです。
function get_theme_mod( $name, $default = false ) {
$mods = get_theme_mods();
if ( isset( $mods[ $name ] ) )
return apply_filters( "theme_mod_$name", $mods[ $name ] );
return apply_filters( "theme_mod_$name", sprintf( $default, get_template_directory_uri(), get_stylesheet_directory_uri() ) );
}
get_theme_mods()も同じファイルに実装されています。
function get_theme_mods() {
$theme_slug = get_option( 'stylesheet' );
if ( false === ( $mods = get_option( "theme_mods_$theme_slug" ) ) ) {
$theme_name = get_current_theme();
$mods = get_option( "mods_$theme_name" ); // Deprecated location.
if ( is_admin() && false !== $mods ) {
update_option( "theme_mods_$theme_slug", $mods );
delete_option( "mods_$theme_name" );
}
}
return $mods;
}
get_theme_mods()は取得関数ですが、オプションの設定はadd_option()、更新はupdate_option()、またオプションの削除関数としてremove_theme_mods()があります。add_option()とupdate_option()はwp-includes/functions.phpに実装されています。
テーマの切り替えなどを行うと、これらの関数が実行されるようです。
5.ナビゲーションの出力

最後に、次の部分でナビゲーションを出力します。
<nav id="access" role="navigation">
<h3 class="assistive-text"><?php _e( 'Main menu', 'twentyeleven' ); ?></h3>
<?php /* Allow screen readers / text browsers to skip the navigation menu and get right to the good stuff. */ ?>
<div class="skip-link"><a class="assistive-text" href="#content" title="<?php esc_attr_e( 'Skip to primary content', 'twentyeleven' ); ?>"><?php _e( 'Skip to primary content', 'twentyeleven' ); ?></a></div>
<div class="skip-link"><a class="assistive-text" href="#secondary" title="<?php esc_attr_e( 'Skip to secondary content', 'twentyeleven' ); ?>"><?php _e( 'Skip to secondary content', 'twentyeleven' ); ?></a></div>
<?php /* Our navigation menu. If one isn't filled out, wp_nav_menu falls back to wp_page_menu. The menu assiged to the primary position is the one used. If none is assigned, the menu with the lowest ID is used. */ ?>
<?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?>
</nav><!-- #access -->
以下は出力例です。
<nav id="access" role="navigation">
<h3 class="assistive-text">メインメニュー</h3>
<div class="skip-link"><a class="assistive-text" href="#content" title="メインコンテンツへ移動">メインコンテンツへ移動</a></div>
<div class="skip-link"><a class="assistive-text" href="#secondary" title="サブコンテンツへ移動">サブコンテンツへ移動</a></div>
<div class="menu"><ul><li class="current_page_item"><a href="http://localhost/wordpress321/" title="ホーム">ホーム</a></li><li class="page_item page-item-2"><a href="http://localhost/wordpress321/?page_id=2" title="サンプルページ">サンプルページ</a></li></ul></div>
</nav><!-- #access -->
wp_nav_menu()はナビゲーションメニューを出力するための関数で、wp-includes/nav-menu-template.phpに実装されています(掲載は割愛)。wp_nav_menu()には色々なオプションがありますが、詳細は別途エントリーしたいと思います。
Twenty Elevenテーマでは、テーマ内で使用する場所(ロケーション)を示す「theme_location」のみを設定しています。「theme_location」の値「primary」は、functions.phpにregister_nav_menu()で設定しています。
// This theme uses wp_nav_menu() in one location.
register_nav_menu( 'primary', __( 'Primary Menu', 'twentyeleven' ) );
functions.phpにregister_nav_menu()を追加していけば、ロケーションのバリエーションを増やすことができます。
register_nav_menu( 'secondary', 'フッターメニュー' );
register_nav_menu()で複数のロケーションをまとめて設定することもできます。
register_nav_menus( array(
'primary' => __( 'Primary Navigation', 'twentyten' ),
'secondary' => 'フッターメニュー',
'thirdly' => 'サイドメニュー',
) );
肝心のメニューの内容は、管理画面の「外観」→「メニュー」で設定します。
デフォルト状態では何も設定されていないので、先程の「フッターメニュー」用のメニュー内容を作りたい場合は、「メニューの名前」に「フッター」など任意の名称を入力して「メニューを作成」をクリック。

作成すると左側にメニュー項目として「カスタムリンク」「固定ページ」「カテゴリー」などがアクティブになり、同時に「register_nav_menus」に対応する「テーマの場所(ロケーション)」も表示されます。

あとはそれぞれのロケーションに作成したメニューを作って「保存」をクリックします。フッターメニューは、テーマの「フッター」に次の記述すれば表示されます。
<?php wp_nav_menu( array( 'theme_location' => 'secondary' ) ); ?>
WordPressのTwenty Elevenテーマ解説:ヘッダー (header.php):その2
WordPressの勉強も兼ねて、Twenty Elevenテーマの各テンプレートについて解説しています。確認バージョンは3.2.1です。
今回は「WordPressのTwenty Elevenテーマ解説:ヘッダー (header.php):その1」の続きです。
ヘッダー (header.php):その2
Twenty Elevenテーマの「ヘッダー (header.php)」は、スクリーンショットの赤枠で示す、WordPressのすべてのページのヘッダー部分(DOCTYPE~<div id="main">まで)に対応しています。
テンプレートのソースコードは次のとおりです。この回で説明するのは青色で示す部分です。
<?php
/**
* The Header for our theme.
*
* Displays all of the <head> section and everything up till <div id="main">
*
* @package WordPress
* @subpackage Twenty_Eleven
* @since Twenty Eleven 1.0
*/
?><!DOCTYPE html>
<!--[if IE 6]>
<html id="ie6" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 7]>
<html id="ie7" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 8]>
<html id="ie8" <?php language_attributes(); ?>>
<![endif]-->
<!--[if !(IE 6) | !(IE 7) | !(IE 8) ]><!-->
<html <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width" />
<title><?php
/*
* Print the <title> tag based on what is being viewed.
*/
global $page, $paged;
wp_title( '|', true, 'right' );
// Add the blog name.
bloginfo( 'name' );
// Add the blog description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
echo " | $site_description";
// Add a page number if necessary:
if ( $paged >= 2 || $page >= 2 )
echo ' | ' . sprintf( __( 'Page %s', 'twentyeleven' ), max( $paged, $page ) );
?></title>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script>
<![endif]-->
<?php
/* We add some JavaScript to pages with the comment form
* to support sites with threaded comments (when in use).
*/
if ( is_singular() && get_option( 'thread_comments' ) )
wp_enqueue_script( 'comment-reply' );
/* Always have wp_head() just before the closing </head>
* tag of your theme, or you will break many plugins, which
* generally use this hook to add elements to <head> such
* as styles, scripts, and meta tags.
*/
wp_head();
?>
</head>
<body <?php body_class(); ?>>
<div id="page" class="hfeed">
<header id="branding" role="banner">
<hgroup>
<h1 id="site-title"><span><a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></span></h1>
<h2 id="site-description"><?php bloginfo( 'description' ); ?></h2>
</hgroup>
<?php
// Check to see if the header image has been removed
$header_image = get_header_image();
if ( ! empty( $header_image ) ) :
?>
<a href="<?php echo esc_url( home_url( '/' ) ); ?>">
<?php
// The header image
// Check if this is a post or page, if it has a thumbnail, and if it's a big one
if ( is_singular() &&
has_post_thumbnail( $post->ID ) &&
( /* $src, $width, $height */ $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), array( HEADER_IMAGE_WIDTH, HEADER_IMAGE_WIDTH ) ) ) &&
$image[1] >= HEADER_IMAGE_WIDTH ) :
// Houston, we have a new header image!
echo get_the_post_thumbnail( $post->ID, 'post-thumbnail' );
else : ?>
<img src="<?php header_image(); ?>" width="<?php echo HEADER_IMAGE_WIDTH; ?>" height="<?php echo HEADER_IMAGE_HEIGHT; ?>" alt="" />
<?php endif; // end check for featured image or standard header ?>
</a>
<?php endif; // end check for removed header image ?>
<?php
// Has the text been hidden?
if ( 'blank' == get_header_textcolor() ) :
?>
<div class="only-search<?php if ( ! empty( $header_image ) ) : ?> with-image<?php endif; ?>">
<?php get_search_form(); ?>
</div>
<?php
else :
?>
<?php get_search_form(); ?>
<?php endif; ?>
<nav id="access" role="navigation">
<h3 class="assistive-text"><?php _e( 'Main menu', 'twentyeleven' ); ?></h3>
<?php /* Allow screen readers / text browsers to skip the navigation menu and get right to the good stuff. */ ?>
<div class="skip-link"><a class="assistive-text" href="#content" title="<?php esc_attr_e( 'Skip to primary content', 'twentyeleven' ); ?>"><?php _e( 'Skip to primary content', 'twentyeleven' ); ?></a></div>
<div class="skip-link"><a class="assistive-text" href="#secondary" title="<?php esc_attr_e( 'Skip to secondary content', 'twentyeleven' ); ?>"><?php _e( 'Skip to secondary content', 'twentyeleven' ); ?></a></div>
<?php /* Our navigation menu. If one isn't filled out, wp_nav_menu falls back to wp_page_menu. The menu assiged to the primary position is the one used. If none is assigned, the menu with the lowest ID is used. */ ?>
<?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?>
</nav><!-- #access -->
</header><!-- #branding -->
<div id="main">
1.link要素の出力
スタイルシートとピンバックのlink要素を出力します。link要素のhref属性の出力にはbloginfo()を利用しています。
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
その1でも解説していますが、bloginfo()はwp-includes/general-template.phpに実装されていて、get_bloginfo()をキックしています。get_bloginfo()については「その1」の4項を参照してください。
wp-includes/general-template.php
function bloginfo( $show='' ) {
echo get_bloginfo( $show, 'display' );
}
2.script要素の出力
ブラウザがIEでバージョンがIE9以下の場合、script要素にget_template_directory_uri()を組み合わせて、html5.jsを読み込みます。
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script>
<![endif]-->
script要素のsrc属性は、
http://user-domain/wp-content/themes/twentyeleven/js/html5.js
という風に、Twenty Elevenテーマに含まれているhtml5.jsのURLを出力します。
get_template_directory_uri()はテーマディレクトリのURLを出力する関数で、wp-includes/theme.phpに実装されています。
wp-includes/theme.php
function get_template_directory_uri() {
$template = get_template();
$theme_root_uri = get_theme_root_uri( $template );
$template_dir_uri = "$theme_root_uri/$template";
return apply_filters( 'template_directory_uri', $template_dir_uri, $template, $theme_root_uri );
}
get_template()もwp-includes/theme.phpに実装されています。
function get_template() {
return apply_filters('template', get_option('template'));
}
get_template()は何をやっているのか分かりにくいのですが、まずget_option()の結果を取得し、その後apply_filters()を実行しています。つまり、フックポイント「template」を使ってget_option()で取得した内容をフィルタできるということです。
例えば次のプラグインを適用すれば、get_template()の出力結果の末尾に「hoge」という文字列を追加できます。
<?php
/*
Plugin Name: hoge
Description: hoge
Version: 1.0
*/
function hoge($template) {
return $template . "hoge";
}
add_filter('template', 'hoge', $template);
?>
get_option()はwp-includes/functions.phpに実装されており(コード掲載は割愛)、get_option('template')は「twentyeleven」という文字列を返却します。
get_option()を利用すればさまざまなオプションデータを取得できるようです。get_option()のパラメータに設定可能な値はOption Referenceを参照してください。
get_option()の中でwp_load_alloptions()という関数を実行しているので、以下の1行を実行すればどのようなオプションがあるか分かるかもしれません。get_bloginfo()の一部のデータもget_option()を利用しているようです。
var_dump(wp_load_alloptions());
話を戻して、get_theme_root_uri()はWordPressのthemesディレクトリに対応するURLを取得する関数で、wp-includes/theme.phpに実装されています(掲載は割愛)。
$theme_root_uri = get_theme_root_uri( $template );
なお、get_theme_root_uri()の中でさらにcontent_url()という関数を起動しています。content_url()はプロトコル(http/https)を決める役割と、パラメータに指定した文字列をURLの末尾に追加する役割があるようです。wp-includes/link-template.phpに実装されています。
3.コメント返信用JavaScriptライブラリの出力
シングルページかつスレッドコメントに対応している場合、コメント返信用JavaScriptライブラリのscript要素を出力します。
if ( is_singular() && get_option( 'thread_comments' ) )
wp_enqueue_script( 'comment-reply' );
出力結果は次のようになります。
<script type='text/javascript' src='http://use-domain/wordpress/wp-includes/js/comment-reply.js?ver=20090102'></script>
is_singular()は、シングルページ (固定ページ、個別投稿ページ、添付ファイルページ)であることを判定する関数で、wp-includes/query.phpに実装されています(掲載は割愛)。is_single()、is_page() 、is_attachment() のいずれかがtrueである場合にtrueを返却します。
wp_enqueue_script()でscript要素を出力します。この関数については次項で解説します。
4.wp_enqueue_script()について
wp_enqueue_script()は、同一のJavaScriptライブラリを重複して出力させない役割があります。
今回の例で言うと、プラグイン内で
wp_enqueue_script('comment-reply');
を使ってコメントスレッド用のライブラリを出力する指定を行っておけば、コメントスレッド用ライブラリのscript要素は、Twenty Elevenテーマのヘッダーに記述されている、
wp_enqueue_script( 'comment-reply' );
とあわせて1回しか出力しません。
よくあるケースとして、プラグインでjqueryライブラリを使用する場合、プラグインに次のように記述します。
<?php
function my_scripts_method() {
wp_enqueue_script( 'jquery' );
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
?>
wp_enqueue_script()はwp-includes/functions.wp-scripts.phpに実装されています。デフォルトで登録されているライブラリは、wp-includes/script-loader.phpのwp_default_scripts()で確認できます。
wp_enqueue_script()のパラメータは次のようになっています。必須パラメータは$handleのみです。
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer )
- $handle:識別名
- $src:指定するライブラリのパス
- $deps:依存するライブラリの識別名を配列で記述。例:array('scriptaculous')
- $ver:ライブラリのバージョン
- $in_footer:ライブラリをwp_footer()で配置(true/false)※デフォルトはfalse
5.wp_head()
wp_head()はテーマを作成するときに必ず必要なもので、通常はhead要素の終了タグの直前に記述します。wp_head()を記述した部分に、プラグインで定義したスクリプトやスタイルのための各要素が出力されます。
wp_head()は「wp_head」フックポイントを実行するためだけの機能をもち、wp-includes/general-template.phpに実装されています。
function wp_head() {
do_action('wp_head');
}
プラグインなどでは次のように「wp_head」フックポイントに登録します。この場合はstyle要素を出力します。
<?php
/*
Plugin Name: add_style
Description: add_style
Version: 1.0
*/
function add_style() {
echo '<style type="text/css">/* ... */</style>';
}
add_action('wp_head', 'add_style');
?>
ちなみにデフォルト状態で「wp_head」フックポイントには色々なものが登録されていて、メインページでは次のような内容を出力します。
<link rel="alternate" type="application/rss+xml" title="My First Blog » フィード" href="http://user-domain/wordpress/?feed=rss2" />
<link rel="alternate" type="application/rss+xml" title="My First Blog » コメントフィード" href="http://user-domain/wordpress/?feed=comments-rss2" />
<link rel='stylesheet' id='admin-bar-css' href='http://user-domain/wordpress/wp-includes/css/admin-bar.css?ver=20110622' type='text/css' media='all' />
<script type='text/javascript' src='http://user-domain/wordpress/wp-includes/js/l10n.js?ver=20101110'></script>
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://user-domain/wordpress/xmlrpc.php?rsd" />
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://user-domain/wordpress/wp-includes/wlwmanifest.xml" />
<link rel='index' title='My First Blog' href='http://user-domain/wordpress' />
<meta name="generator" content="WordPress 3.2.1" />
<style type="text/css" media="print">#wpadminbar { display:none; }</style>
<style type="text/css" media="screen">
html { margin-top: 28px !important; }
* html body { margin-top: 28px !important; }
</style>
「wp_head」フックポイントにデフォルトで登録されているものを削除したい場合は、remove_action()を使用します。例えば
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://user-domain/wordpress/xmlrpc.php?rsd" />
が不要な場合は次の1行をテーマのfunctions.phpに記述します。
remove_action('wp_head', 'rsd_link');
デフォルトで「wp_head」フックポイントに登録されているアクションは、wp-includes/default-filters.phpに記述されています。下記は「wp_head」分のみ抜粋したものです。
add_action( 'wp_head', 'wp_enqueue_scripts', 1 );
add_action( 'wp_head', 'feed_links', 2 );
add_action( 'wp_head', 'feed_links_extra', 3 );
add_action( 'wp_head', 'rsd_link' );
add_action( 'wp_head', 'wlwmanifest_link' );
add_action( 'wp_head', 'index_rel_link' );
add_action( 'wp_head', 'parent_post_rel_link', 10, 0 );
add_action( 'wp_head', 'start_post_rel_link', 10, 0 );
add_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );
add_action( 'wp_head', 'locale_stylesheet' );
add_action( 'wp_head', 'noindex', 1 );
add_action( 'wp_head', 'wp_print_styles', 8 );
add_action( 'wp_head', 'wp_print_head_scripts', 9 );
add_action( 'wp_head', 'wp_generator' );
add_action( 'wp_head', 'rel_canonical' );
add_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );
WordPressのTwenty Elevenテーマ解説:ヘッダー (header.php):その1
WordPressの勉強も兼ねて、Twenty Elevenテーマの各テンプレートについて解説しています。確認バージョンは3.2.1です。
ヘッダー (header.php):その1
今回はヘッダーです。このエントリーでヘッダーテンプレートのすべてを紹介する予定でしたが、コードの深いところまでトレースしていくと予想以上に長くなってしまい、あきらめて数回に分けることにしました。
説明の中では、apply_filters()の役割や、_e()と__()の違い、bloginfo()とget_bloginfo()の違いなどについても触れています。
Twenty Elevenテーマの「ヘッダー (header.php)」は、スクリーンショットの赤枠で示す、WordPressのすべてのページのヘッダー部分(DOCTYPE~<div id="main">まで)に対応しています。
テンプレートのソースコードは次のとおりです。この回で説明するのは青色で示す部分です。
<?php
/**
* The Header for our theme.
*
* Displays all of the <head> section and everything up till <div id="main">
*
* @package WordPress
* @subpackage Twenty_Eleven
* @since Twenty Eleven 1.0
*/
?><!DOCTYPE html>
<!--[if IE 6]>
<html id="ie6" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 7]>
<html id="ie7" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 8]>
<html id="ie8" <?php language_attributes(); ?>>
<![endif]-->
<!--[if !(IE 6) | !(IE 7) | !(IE 8) ]><!-->
<html <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width" />
<title><?php
/*
* Print the <title> tag based on what is being viewed.
*/
global $page, $paged;
wp_title( '|', true, 'right' );
// Add the blog name.
bloginfo( 'name' );
// Add the blog description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
echo " | $site_description";
// Add a page number if necessary:
if ( $paged >= 2 || $page >= 2 )
echo ' | ' . sprintf( __( 'Page %s', 'twentyeleven' ), max( $paged, $page ) );
?></title>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script>
<![endif]-->
<?php
/* We add some JavaScript to pages with the comment form
* to support sites with threaded comments (when in use).
*/
if ( is_singular() && get_option( 'thread_comments' ) )
wp_enqueue_script( 'comment-reply' );
/* Always have wp_head() just before the closing </head>
* tag of your theme, or you will break many plugins, which
* generally use this hook to add elements to <head> such
* as styles, scripts, and meta tags.
*/
wp_head();
?>
</head>
<body <?php body_class(); ?>>
<div id="page" class="hfeed">
<header id="branding" role="banner">
<hgroup>
<h1 id="site-title"><span><a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></span></h1>
<h2 id="site-description"><?php bloginfo( 'description' ); ?></h2>
</hgroup>
<?php
// Check to see if the header image has been removed
$header_image = get_header_image();
if ( ! empty( $header_image ) ) :
?>
<a href="<?php echo esc_url( home_url( '/' ) ); ?>">
<?php
// The header image
// Check if this is a post or page, if it has a thumbnail, and if it's a big one
if ( is_singular() &&
has_post_thumbnail( $post->ID ) &&
( /* $src, $width, $height */ $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), array( HEADER_IMAGE_WIDTH, HEADER_IMAGE_WIDTH ) ) ) &&
$image[1] >= HEADER_IMAGE_WIDTH ) :
// Houston, we have a new header image!
echo get_the_post_thumbnail( $post->ID, 'post-thumbnail' );
else : ?>
<img src="<?php header_image(); ?>" width="<?php echo HEADER_IMAGE_WIDTH; ?>" height="<?php echo HEADER_IMAGE_HEIGHT; ?>" alt="" />
<?php endif; // end check for featured image or standard header ?>
</a>
<?php endif; // end check for removed header image ?>
<?php
// Has the text been hidden?
if ( 'blank' == get_header_textcolor() ) :
?>
<div class="only-search<?php if ( ! empty( $header_image ) ) : ?> with-image<?php endif; ?>">
<?php get_search_form(); ?>
</div>
<?php
else :
?>
<?php get_search_form(); ?>
<?php endif; ?>
<nav id="access" role="navigation">
<h3 class="assistive-text"><?php _e( 'Main menu', 'twentyeleven' ); ?></h3>
<?php /* Allow screen readers / text browsers to skip the navigation menu and get right to the good stuff. */ ?>
<div class="skip-link"><a class="assistive-text" href="#content" title="<?php esc_attr_e( 'Skip to primary content', 'twentyeleven' ); ?>"><?php _e( 'Skip to primary content', 'twentyeleven' ); ?></a></div>
<div class="skip-link"><a class="assistive-text" href="#secondary" title="<?php esc_attr_e( 'Skip to secondary content', 'twentyeleven' ); ?>"><?php _e( 'Skip to secondary content', 'twentyeleven' ); ?></a></div>
<?php /* Our navigation menu. If one isn't filled out, wp_nav_menu falls back to wp_page_menu. The menu assiged to the primary position is the one used. If none is assigned, the menu with the lowest ID is used. */ ?>
<?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?>
</nav><!-- #access -->
</header><!-- #branding -->
<div id="main">
1.html要素のdir属性出力
DOCTYPE宣言の下に、IEの条件付きコメントの中にlanguage_attributes()が使われています。
<!--[if IE 6]>
<html id="ie6" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 7]>
<html id="ie7" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 8]>
<html id="ie8" <?php language_attributes(); ?>>
<![endif]-->
<!--[if !(IE 6) | !(IE 7) | !(IE 8) ]><!-->
<html <?php language_attributes(); ?>>
<!--<![endif]-->
この関数は、次のような内容を出力します。
dir="ltr" lang="ja"
まず、dir属性の出力について解説します。
language_attributes()はwp-includes/general-template.phpに実装されています。dir属性の出力は赤色部分が対応します。
wp-includes/general-template.php
function language_attributes($doctype = 'html') {
$attributes = array();
$output = '';
if ( function_exists( 'is_rtl' ) )
$attributes[] = 'dir="' . ( is_rtl() ? 'rtl' : 'ltr' ) . '"';
if ( $lang = get_bloginfo('language') ) {
if ( get_option('html_type') == 'text/html' || $doctype == 'html' )
$attributes[] = "lang=\"$lang\"";
if ( get_option('html_type') != 'text/html' || $doctype == 'xhtml' )
$attributes[] = "xml:lang=\"$lang\"";
}
$output = implode(' ', $attributes);
$output = apply_filters('language_attributes', $output);
echo $output;
}
function_exists()はパラメータに指定した関数が定義されている場合にtrueを返却するPHPの関数です。ここではis_rtlという関数定義を判断して、定義されていれば、配列変数$attributesに「dir="rtl"」または「dir="ltr"」を設定します。
dir 属性は要素のテキストの方向性を指定するためのもので、値は次の意味をもちます。
- ltr:該当の要素のコンテンツが明示的に左から右向きに組み込まれたテキスト
- rtl:該当の要素のコンテンツが明示的に右から左向きに組み込まれたテキスト
どちらの値を設定するかは、is_rtl()で判定しています。is_rtl()はwp-includes/locale.phpの最後に実装されています。
wp-includes/locale.php
function is_rtl() {
global $wp_locale;
return $wp_locale->is_rtl();
}
話がちょっと長くなりますが、変数$wp_localeはwp-settings.phpで定義しています。
$wp_locale = new WP_Locale();
WP_Localeクラスは先程のwp-includes/locale.phpで宣言されています。
/**
* Class that loads the calendar locale.
*
* @since 2.1.0
*/
class WP_Locale {
// ...
}
ということで、is_rtl()の処理にある、
return $wp_locale->is_rtl();
は、WP_Localeクラスの中に定義されていることが分かります。
class WP_Locale {
// ...
function is_rtl() {
return 'rtl' == $this->text_direction;
}
}
変数$text_directionは同じクラス内に記述されています。値は「ltr」固定のようです。
var $text_direction = 'ltr';
この部分を「rtl」に書き換えると、ページは次のようになります。
2.html要素のlang属性出力
1項で説明したlanguage_attributes()の赤色部分でlang属性も出力します。
function language_attributes($doctype = 'html') {
$attributes = array();
$output = '';
if ( function_exists( 'is_rtl' ) )
$attributes[] = 'dir="' . ( is_rtl() ? 'rtl' : 'ltr' ) . '"';
if ( $lang = get_bloginfo('language') ) {
if ( get_option('html_type') == 'text/html' || $doctype == 'html' )
$attributes[] = "lang=\"$lang\"";
if ( get_option('html_type') != 'text/html' || $doctype == 'xhtml' )
$attributes[] = "xml:lang=\"$lang\"";
}
$output = implode(' ', $attributes);
$output = apply_filters('language_attributes', $output);
echo $output;
}
処理中で使われているget_bloginfo()はパラメータに指定した情報を取得する関数で、wp-includes/general-template.phpに実装されています。今回の該当部分のみ抜粋して掲載します。
function get_bloginfo( $show = '', $filter = 'raw' ) {
// ...
switch( $show ) {
case 'language':
$output = get_locale();
$output = str_replace('_', '-', $output);
break;
}
// ...
return $output;
}
get_bloginfo()の中で使われているget_locale()は、wp-includes/l10n.phpに実装されています。
wp-includes/l10n.php
function get_locale() {
global $locale;
if ( isset( $locale ) )
return apply_filters( 'locale', $locale );
// WPLANG is defined in wp-config.
if ( defined( 'WPLANG' ) )
$locale = WPLANG;
// If multisite, check options.
if ( is_multisite() && !defined('WP_INSTALLING') ) {
$ms_locale = get_option('WPLANG');
if ( $ms_locale === false )
$ms_locale = get_site_option('WPLANG');
if ( $ms_locale !== false )
$locale = $ms_locale;
}
if ( empty( $locale ) )
$locale = 'en_US';
return apply_filters( 'locale', $locale );
}
今回は赤色部分のコードで「ja」という文字列を返却します。理由は、WordPressの日本語パッケージではwp-config.phpに次の内容が設定されているからです。
define('WPLANG', 'ja');
次に、language_attributes()の中にあるget_option()は、管理画面の「設定」メニューの任意の項目などを取得する関数で、DBのwp_optionsテーブル(wp_が接頭辞の場合)に対応しているようです。
if ( $lang = get_bloginfo('language') ) {
if ( get_option('html_type') == 'text/html' || $doctype == 'html' )
$attributes[] = "lang=\"$lang\"";
if ( get_option('html_type') != 'text/html' || $doctype == 'xhtml' )
$attributes[] = "xml:lang=\"$lang\"";
}
ここでは、「html_type」を指定していますが、wp_optionsテーブルには該当のデータがないようなので(設定不足でしたらすいません)、変数$doctypeの値を判定します。変数$doctypeにはデフォルトで「html」が設定されているので、配列変数$attributesには「html="ja"」が設定されます。
あとは、implode()でdir属性とhtml属性を半角スペースで結合して出力します。
$output = implode(' ', $attributes);
$output = apply_filters('language_attributes', $output);
echo $output;
3.apply_filters()について
テンプレートから話がそれますが、前項の赤色のapply_filters()について解説します。
apply_filters()は「WordPressのTwenty Elevenテーマ解説:メインインデックスのテンプレート (index.php)」で解説した、do_action()を使ってフックポイントを追加する動作に似ています。apply_filters()の役割は、フィルタ(出力内容をプラグインなどで書き換える)を追加するためのものです。
例えば、
apply_filters('language_attributes', $output);
は、フックポイント「language_attributes」を追加し、書き換えの対象が$outputであることを示します。ここでは変数を1つしか設定していませんが、複数指定し、それらをフィルタの処理判定などに使うこともできます。
プラグインを作成している方はすでにご存知と思いますが、add_filter()を使えばフックポイントに任意のフィルタを追加できます。
今回の場合、プラグインで次のコードを記述すれば、フックポイント「language_attributes」、つまりapply_filters('language_attributes', $output)の実行時にbar()が起動され、html要素の最後に「class="bar"」が追加されます。
<?php
/*
Plugin Name: Bar
Description: Bar
Version: 1.0
*/
function bar($options) {
return $options . " class=\"bar\"";
}
add_filter('language_attributes', 'bar', $options);
?>
4.meta要素のcharset属性の出力
meta要素のcharset属性値の出力には、bloginfo()を利用しています。
<meta charset="<?php bloginfo( 'charset' ); ?>" />
bloginfo()はwp-includes/general-template.phpに実装されていて、先述のget_bloginfo()をキックしています。bloginfo()はget_bloginfo()の結果をechoしているのが大きな違いです。
wp-includes/general-template.php
function bloginfo( $show='' ) {
echo get_bloginfo( $show, 'display' );
}
また、bloginfo()からget_bloginfo()をキックした場合はget_bloginfo()の中でapply_filters()が動作します。厳密に言えば、キックしなくてもget_bloginfo()の第2パラメータに「display」を指定すればapply_filters()が動作します。フックポイントは「bloginfo_url」と「bloginfo」の2種類があります。
get_bloginfo()でapply_filters()が起動する部分のみ抜粋しておきます。
function get_bloginfo( $show = '', $filter = 'raw' ) {
// ...
$url = true;
if (strpos($show, 'url') === false &&
strpos($show, 'directory') === false &&
strpos($show, 'home') === false)
$url = false;
if ( 'display' == $filter ) {
if ( $url )
$output = apply_filters('bloginfo_url', $output, $show);
else
$output = apply_filters('bloginfo', $output, $show);
}
return $output;
}
$urlがtrueになる条件は、get_bloginfo()の第1パラメータが次のもの以外が設定されている場合です。
- url
- directory
- home
$urlがtrueになれば「bloginfo_url」のフィルタが登録されます。$urlがfalseになれば「bloginfo」のフィルタが登録されます(間違ってたらすいません)。
5.title要素の出力
次の部分でtitle要素を出力します。
<title><?php
/*
* Print the <title> tag based on what is being viewed.
*/
global $page, $paged;
wp_title( '|', true, 'right' );
// Add the blog name.
bloginfo( 'name' );
// Add the blog description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
echo " | $site_description";
// Add a page number if necessary:
if ( $paged >= 2 || $page >= 2 )
echo ' | ' . sprintf( __( 'Page %s', 'twentyeleven' ), max( $paged, $page ) );
?></title>
トップページでページ送りをしていて3ページ目であれば、次のような表示になります。
![]()
表示内容の意味は次の通りです。
ブログ名 | キャッチフレーズ | ページ番号
変数$pagedには、ページ送り(ページング)を行った場合に、URLのクエリーに設定される「paged」の値が設定されます。$pageには特に値が設定されていないようです(間違っていたらすいません)。
global $page, $paged;
内容の説明が前後しますが、先にページ番号についてまとめて説明します。ページ番号が2以上の場合に、次の部分でtitle要素に出力します。
if ( $paged >= 2 || $page >= 2 )
echo ' | ' . sprintf( __( 'Page %s', 'twentyeleven' ), max( $paged, $page
max()は、設定されたものから一番大きい値を返却するPHPの関数です。
__()は、日本語ローカライズを行うためのものです。第1パラメータにローカライズ対象の文字列、第2パラメータがドメイン名を指定します。wp-includes/l10n.phpに実装されています。
wp-includes/l10n.php
function __( $text, $domain = 'default' ) {
return translate( $text, $domain );
}
「WordPressのTwenty Elevenテーマ解説:メインインデックスのテンプレート (index.php)」で_e()について紹介しましたが、2つの関数の違いは、__()はreturnしているだけですが、_e()はechoしています。
function _e( $text, $domain = 'default' ) {
echo translate( $text, $domain );
}
wp_title()はページタイトルを表示するテンプレートタグで、利用するページで処理が異なります。
wp_title( '|', true, 'right' );
この関数はwp-includes/general-template.phpに実装されています(長いので掲載は省略)。パラメータの意味は次の通りです。
- 第1パラメータ:セパレータ文字列
- 第2パラメータ:wp_titleの実行結果をechoで表示する・しない(true/false)
- 第3パラメータ:セパレータの位置(right/left)
bloginfo('name')では、ブログ名を出力します。
bloginfo( 'name' );
管理画面の「設定」→「一般」→「キャッチフレーズ」は次の部分で出力します。
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
echo " | $site_description";
is_home()はサイトのトップページを表示していることを判定する関数で、wp-includes/query.phpに実装されています。
wp-includes/query.php
function is_home() {
global $wp_query;
if ( ! isset( $wp_query ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
return false;
}
return $wp_query->is_home();
}
is_front_page()は、サイトのフロントページが表示されているかどうかを判定する関数で、is_home()同様、wp-includes/query.phpに実装されています。
function is_front_page() {
global $wp_query;
if ( ! isset( $wp_query ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
return false;
}
return $wp_query->is_front_page();
}
is_front_page()でtrueを返却するのは、管理画面の「設定」→「表示設定」→「フロントページの表示」にて、「最新の投稿」を選択して、最新の投稿ページが表示されている場合および、「固定ページ」を選択して、「フロントページ」に指定したページが表示されている場合です。
WordPressのTwenty Elevenテーマ解説:メインインデックスのテンプレート (index.php)
WordPressの勉強も兼ねて、Twenty Elevenテーマの各テンプレートについて解説してみたいと思います。確認バージョンは3.2.1です。
メインインデックスのテンプレート (index.php)
Twenty Elevenテーマの「メインインデックスのテンプレート (index.php)」で出力されるページは次のようになります。
テンプレートのソースコードは次のとおりです。
<?php
/**
* The main template file.
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package WordPress
* @subpackage Twenty_Eleven
*/
get_header(); ?>
<div id="primary">
<div id="content" role="main">
<?php if ( have_posts() ) : ?>
<?php twentyeleven_content_nav( 'nav-above' ); ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<?php twentyeleven_content_nav( 'nav-below' ); ?>
<?php else : ?>
<article id="post-0" class="post no-results not-found">
<header class="entry-header">
<h1 class="entry-title"><?php _e( 'Nothing Found', 'twentyeleven' ); ?></h1>
</header><!-- .entry-header -->
<div class="entry-content">
<p><?php _e( 'Apologies, but no results were found for the requested archive. Perhaps searching will help find a related post.', 'twentyeleven' ); ?></p>
<?php get_search_form(); ?>
</div><!-- .entry-content -->
</article><!-- #post-0 -->
<?php endif; ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
1.ヘッダー情報の出力
ヘッダー情報はget_header()で出力します。
<?php
…中略…
get_header(); ?>
ヘッダー情報は、トップページの赤枠部分が対応します。
get_header()はwp-includes/general-template.phpに実装されています。
wp-includes/general-template.php
function get_header( $name = null ) {
do_action( 'get_header', $name );
$templates = array();
if ( isset($name) )
$templates[] = "header-{$name}.php";
$templates[] = 'header.php';
// Backward compat code will be removed in a future release
if ('' == locate_template($templates, true))
load_template( ABSPATH . WPINC . '/theme-compat/header.php');
}
do_action()はフックポイント「get_header」の作成を行っています。
do_action( 'get_header', $name );
プラグインを作成している方はすでにご存知と思いますが、add_action()を使えばフックポイントに任意のアクションを追加できます。
例えばプラグインで次のコードを記述すれば、フックポイント「get_header」、つまりdo_action('get_header')の実行時にfoo()が起動され、doctype宣言の前に「foo」が出力されます。
<?php
/*
Plugin Name: Foo
Description: Foo
Version: 1.0
*/
function foo() {
echo "foo";
}
add_action('get_header', 'foo');
?>
話を戻して、get_header()では、パラメータに設定した文字列をテンプレート名として利用します。「get_header('foo')」と書いておけば、「header-foo.php」を「header.php」の代わりにロードします。パラメータの設定がなければ「header.php」をロードします。
$templates = array();
if ( isset($name) )
$templates[] = "header-{$name}.php";
$templates[] = 'header.php';
2.記事の有無判定
次のif文では、記事の有無判定により処理を振り分けています。
<?php if ( have_posts() ) : ?>
// 記事が投稿されている場合の処理
<?php else : ?>
// 記事が投稿されていない場合の処理
<?php endif; ?>
have_posts()は投稿記事をチェックする関数で、wp-includes/query.phpに実装されています。
wp-includes/query.php
function have_posts() {
global $wp_query;
return $wp_query->have_posts();
}
投稿記事が存在する場合はtrue、存在しない場合はfalseを返却します。パラメータはありません。ここではhave_posts()をif文で使っていますが、この関数はループ処理で利用することもできます。
if文の中の処理の説明は後回しにして、それぞれどのような出力になるかをご覧ください。
記事が投稿されていない場合(メッセージと検索フォームを出力)
![]()
次に、それぞれの処理について解説します。
3.ナビゲーションの表示
投稿記事がある場合はナビゲーションとコンテンツを出力します。ここではナビゲーションの出力について説明します。該当する処理は次の赤色部分になります。
<?php if ( have_posts() ) : ?>
<?php twentyeleven_content_nav( 'nav-above' ); ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<?php twentyeleven_content_nav( 'nav-below' ); ?>
twentyeleven_content_nav()はTwenty Elevenテーマの独自処理で、表示する記事数が1ページを超える場合に前後のナビゲーションを表示します。1ページの表示記事数は「設定」→「表示設定」→「1ページに表示する最大投稿数」で決まります。
twentyeleven_content_nav()は、テーマのfunctions.phpに実装されています。
functions.php
/**
* Display navigation to next/previous pages when applicable
*/
function twentyeleven_content_nav( $nav_id ) {
global $wp_query;
if ( $wp_query->max_num_pages > 1 ) : ?>
<nav id="<?php echo $nav_id; ?>">
<h3 class="assistive-text"><?php _e( 'Post navigation', 'twentyeleven' ); ?></h3>
<div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">←</span> Older posts', 'twentyeleven' ) ); ?></div>
<div class="nav-next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">→</span>', 'twentyeleven' ) ); ?></div>
</nav><!-- #nav-above -->
<?php endif;
}
「$wp_query->max_num_pages」が最大ページ数です。
さて、ナビゲーションは基本的に記事の上部と下部の2ヶ所に表示されるのですが、このテーマではトップページのみ記事の下部にだけ表示されるように仕込まれています。
この技は、style.cssにある次のセレクタを使って実現しています。
「nav-above」は記事の上部に表示するナビゲーションのid属性値で常に非表示ですが、「paged」はトップページ以外の前後ページでbody要素に与えられるclass属性値で、このときだけdiplayプロパティを「block」に変更しています。
#nav-above {
display: none;
}
.paged #nav-above {
display: block;
}
4.コンテンツの表示
ナビゲーション出力処理にはさまれて、赤色で示すコンテンツ出力処理があります。
<?php if ( have_posts() ) : ?>
<?php twentyeleven_content_nav( 'nav-above' ); ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<?php twentyeleven_content_nav( 'nav-below' ); ?>
while文で、先に説明したhave_posts()を使って判定し、表示する記事があるまで繰り返します。
the_post()は投稿データをロードする関数です。the_post()を実行しただけでは何も出力しません。
余談ですが、while/have_posts()/the_post()の組み合わせは、Movable Typeの次のテンプレートタグを書いた状態とほぼ同じと言えるでしょう。
<mt:Entries>
</mt:Entries>
get_template_part()でコンテンツを出力します。get_template_part()はwp-includes/general-template.phpに実装されています。
wp-includes/general-template.php
function get_template_part( $slug, $name = null ) {
do_action( "get_template_part_{$slug}", $slug, $name );
$templates = array();
if ( isset($name) )
$templates[] = "{$slug}-{$name}.php";
$templates[] = "{$slug}.php";
locate_template($templates, true, false);
}
do_action()でフックポイント「get_template_part_スラッグ名」の作成を行っています。この場合はスラッグ名は「content」なので、フックポイント名は「get_template_part_content」になります。
また、get_header()と同様、第1パラメータと第2パラメータに設定された名前を使ってテンプレートを呼び出します。第2パラメータが設定されていれば、
「スラッグ名-名前.php」でテンプレートを呼び出します。第2パラメータが設定されていなければ、「スラッグ名.php」でテンプレートを呼び出します。
get_template_part()の第1パラメータは「content」ですが、第2パラメータには「get_post_format()」という関数名が設定されています。言い換えると、get_post_format()の実行結果が第2パラメータに設定されることになります。
<?php get_template_part( 'content', get_post_format() ); ?>
このget_post_format()は何者か?ということですが、記事の場合は投稿画面にある「フォーマット」を取得するための関数です。

get_post_format()は、wp-includes/post.phpに実装されています。
wp-includes/post.php
function get_post_format( $post = null ) {
$post = get_post($post);
if ( ! post_type_supports( $post->post_type, 'post-formats' ) )
return false;
$_format = get_the_terms( $post->ID, 'post_format' );
if ( empty( $_format ) )
return false;
$format = array_shift( $_format );
return ( str_replace('post-format-', '', $format->slug ) );
}
つまり、while文の中で実行しているget_post_format()の実行結果は、記事単位に異なります。フォーマットとget_post_format()の実行結果、対応するテンプレートは次のようになります。
| フォーマット | 実行結果 | テンプレート |
|---|---|---|
| 標準 | 0(なし) | content.php |
| アサイド | aside | content-aside.php |
| リンク | link | content-link.php |
| ギャラリー | gallery | content-gallery.php |
| ステータス | status | content-status.php |
| 引用 | quote | content-quote.php |
| 画像 | image | content-image.php |
余談ですが、テーマにあるその他の「content-xx.php」は次のように他のテンプレートに対応しています。
| テンプレート | 利用テンプレート |
|---|---|
| content-intro.php content-feature.php | showcase.php |
| content-page.php | page.php sidebar-page.php |
| content-single.php | single.php |
5.検索フォームの出力
投稿記事がなかった場合には検索フォームを出力します。
<?php else : ?>
<article id="post-0" class="post no-results not-found">
<header class="entry-header">
<h1 class="entry-title"><?php _e( 'Nothing Found', 'twentyeleven' ); ?></h1>
</header><!-- .entry-header -->
<div class="entry-content">
<p><?php _e( 'Apologies, but no results were found for the requested archive. Perhaps searching will help find a related post.', 'twentyeleven' ); ?></p>
<?php get_search_form(); ?>
</div><!-- .entry-content -->
</article><!-- #post-0 -->
_e()は、日本語ローカライズを行うためのものです。第1パラメータにローカライズ対象の文字列、第2パラメータがドメイン名を指定します。
<h1 class="entry-title"><?php _e( 'Nothing Found', 'twentyeleven' ); ?></h1>
検索フォームの出力にget_search_form()を使っています。
<?php get_search_form(); ?>
get_search_form()は、wp-includes/general-template.phpに実装されています。
wp-includes/general-template.php
function get_search_form($echo = true) {
do_action( 'get_search_form' );
$search_form_template = locate_template('searchform.php');
if ( '' != $search_form_template ) {
require($search_form_template);
return;
}
$form = '<form role="search" method="get" id="searchform" action="' . home_url( '/' ) . '" >
<div><label class="screen-reader-text" for="s">' . __('Search for:') . '</label>
<input type="text" value="' . get_search_query() . '" name="s" id="s" />
<input type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" />
</div>
</form>';
if ( $echo )
echo apply_filters('get_search_form', $form);
else
return apply_filters('get_search_form', $form);
}
テーマに「searchform.php」があればその内容を返却します。そうでない場合はget_search_form()の中で生成した検索フォームを返却します。do_action()の動作は前述と同じなので、割愛します。
6.サイドバー情報の出力
サイドバー情報は、トップページの赤枠部分が対応します。
サイドバー情報はget_sidebar()で出力します。
<?php get_sidebar(); ?>
get_sidebar()は、wp-includes/general-template.phpに実装されています。
wp-includes/general-template.php
function get_sidebar( $name = null ) {
do_action( 'get_sidebar', $name );
$templates = array();
if ( isset($name) )
$templates[] = "sidebar-{$name}.php";
$templates[] = 'sidebar.php';
// Backward compat code will be removed in a future release
if ('' == locate_template($templates, true))
load_template( ABSPATH . WPINC . '/theme-compat/sidebar.php');
}
get_sidebar()では、パラメータに設定した文字列をテンプレート名として利用します。「get_sidebar('foo')」と書いておけば、「sidebar-foo.php」を「sidebar.php」の代わりにロードします。
7.フッター情報の出力
フッター情報は、トップページの赤枠部分が対応します。
フッター情報はget_footer()で出力します。
<?php get_footer(); ?>
get_footer()は、wp-includes/general-template.phpに実装されています。
wp-includes/general-template.php
function get_footer( $name = null ) {
do_action( 'get_footer', $name );
$templates = array();
if ( isset($name) )
$templates[] = "footer-{$name}.php";
$templates[] = 'footer.php';
// Backward compat code will be removed in a future release
if ('' == locate_template($templates, true))
load_template( ABSPATH . WPINC . '/theme-compat/footer.php');
}
パラメータの設定やフックポイントの設定はこれまでと同様なので省略します。
WordPress 3でウィジェットを作るカスタマイズ
「WordPress 3のサイドバーにウィジェットを表示するカスタマイズ」の続きで、WordPress 3でウィジェットを作るカスタマイズを紹介します。
1.基本
ウィジェット作成に必要なソースコードは次のようなイメージです。
class WP_Widget_xxx extends WP_Widget {
function WP_Widget_xxx() { }
function form( $instance ) { }
function update( $new_instance, $old_instance ) { }
function widget( $args, $instance ) { }
}
function WP_Widget_xxxInit() {
register_widget('WP_Widget_xxx');
}
add_action('widgets_init', 'WP_Widget_xxxInit');
ソースコードをテーマのfunction.php、あるいはプラグインファイルに記述すれば、ウィジェットが追加される仕組みになっています。
前述のソースコードは3つの部分に大別されます。
- WP_Widgetを継承したクラスWP_Widget_xxxの定義
- ウィジェット登録する関数(WP_Widget_xxxInit)の定義
- add_action()を使って、ウィジェット管理画面を初期化するフックポイントwidgets_initにウィジェット初期化関数(WP_Widget_xxxInit())の登録
処理は3→2→1の順で実行されます。2と3はxxxの部分を任意の名称にするだけでどんなウィジェットにも使いまわせます。3を次のように書けば2を省略できます。
add_action('widgets_init', create_function('', 'return register_widget("WP_Widget_xxx");'));
実際にウィジェットの中身を作るのは1のクラスWP_Widget_xxxで、クラス内で定義する関数は次の4つです。
- コンストラクタ(WP_Widget_xxx)
- form():管理画面のウィジェットにフォームを表示する関数
- update():管理画面のウィジェットの「保存」をクリックしたときに実行される関数
- widget():ウィジェットを表示する関数
ここではデフォルトのカレンダーウィジェットを例に、それぞれの関数の動作について解説します。
カレンダーウィジェット

ウィジェットで表示されたカレンダー

カレンダーウィジェットのソースコード
class WP_Widget_Calendar extends WP_Widget {
function WP_Widget_Calendar() {
$widget_ops = array('classname' => 'widget_calendar',
'description' => __( 'A calendar of your site’s posts') );
$this->WP_Widget('calendar', __('Calendar'), $widget_ops);
}
function widget( $args, $instance ) {
extract($args);
$title = apply_filters('widget_title',
empty($instance['title']) ?
' ' : $instance['title'],
$instance,
$this->id_base);
echo $before_widget;
if ( $title )
echo $before_title . $title . $after_title;
echo '<div id="calendar_wrap">';
get_calendar();
echo '</div>';
echo $after_widget;
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
return $instance;
}
function form( $instance ) {
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
$title = strip_tags($instance['title']);
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>">
<?php _e('Title:'); ?>
</label>
<input class="widefat"
id="<?php echo $this->get_field_id('title'); ?>"
name="<?php echo $this->get_field_name('title'); ?>"
type="text"
value="<?php echo esc_attr($title); ?>" />
</p>
<?php
}
}
function WP_Widget_CalendarInit() {
register_widget('WP_Widget_Calendar');
}
add_action('widgets_init', 'WP_Widget_CalendarInit');
1.コンストラクタ
コンストラクタはウィジェット名の定義、ウィジェットの登録などを行います。カレンダーウィジェットのコンストラクタは次のようになっています。
function WP_Widget_Calendar() {
$widget_ops = array('classname' => 'widget_calendar',
'description' => __( 'A calendar of your site’s posts') );
$this->WP_Widget('calendar', __('Calendar'), $widget_ops);
}
WP_Widget()の引数の意味は次の通りです。
WP_Widget(ウィジェットID, ウィジェット名, ウィジェットオプション, コントロールオプション);
ウィジェットIDは任意の小文字の文字列、ウィジェット名は管理画面のウィジェットタイトルになります。
ウィジェットオプションにはハッシュclassnameとdescriptionを配列で定義でき、descriptionはウィジェットタイトル下の説明文になります。
コントロールオプションには、ウィジェットのサイズを定義するハッシュwidthとheightを配列で定義できます(有効なのはwidthのみの模様)。
$control_ops = array('width' => '300px', 'height' => '300px');
2.form()
form()はウィジェット管理画面のフォームを定義します。フォームを定義することでウィジェットの表示をカスタマイズすることができます。
以下はカレンダーウィジェットのタイトル名を変更するためのフォームです。
function form( $instance ) {
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
$title = strip_tags($instance['title']);
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>">
<?php _e('Title:'); ?>
</label>
<input class="widefat"
id="<?php echo $this->get_field_id('title'); ?>"
name="<?php echo $this->get_field_name('title'); ?>"
type="text"
value="<?php echo esc_attr($title); ?>" />
</p>
<?php
}
関数の引数$instanceにはフォームデータが設定されており、1行目のwp_parse_argsで$instanceをハッシュ形式に変換します。
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
2行目で、ハッシュキーtitleの値から不要なタグを除去します。
$title = strip_tags($instance['title']);
残りの処理で、取得したフォームデータ($title)をフォームに反映させます。
<p>
<label for="<?php echo $this->get_field_id('title'); ?>">
<?php _e('Title:'); ?>
</label>
<input class="widefat"
id="<?php echo $this->get_field_id('title'); ?>"
name="<?php echo $this->get_field_name('title'); ?>"
type="text"
value="<?php echo esc_attr($title); ?>" />
</p>
関数get_field_id()とget_field_name()は上記の処理を流用すれば良いと思います。
参考までに、get_field_id()はwp-includes/widgets.phpにあり、次の処理を行っています。
function get_field_id($field_name) {
return 'widget-' . $this->id_base . '-' . $this->number . '-' . $field_name;
}
get_field_name()もwp-includes/widgets.phpにあり、次の処理を行っています。
function get_field_name($field_name) {
return 'widget-' . $this->id_base . '[' . $this->number . '][' . $field_name . ']';
}
3.update()
update()は、管理画面のウィジェットの「保存」をクリックしたときに実行し、フォームデータを保存します。
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
return $instance;
}
関数の引数$new_instanceは変更後のデータ、$old_instanceは変更前のデータが設定されています。ここでは2行目でハッシュキーtitleの値のみ取り出して返却していますが、単純に次のようにしてもよいでしょう。
function update( $new_instance, $old_instance ) {
return $new_instance;
}
4.widget()
widget()はウィジェットを表示する役割があります。前述のようなフォームデータがある場合、この関数でフォームデータの値を取得し、ウィジェットの表示に反映させます。
function widget( $args, $instance ) {
extract($args);
$title = apply_filters('widget_title', empty($instance['title']) ?
' ' : $instance['title'], $instance, $this->id_base);
echo $before_widget;
if ( $title )
echo $before_title . $title . $after_title;
echo '<div id="calendar_wrap">';
get_calendar();
echo '</div>';
echo $after_widget;
}
関数の引数$instanceは、form()の引数と同様、フォームデータです。
1行目のextractで、引数$argsの内容を配列にセットします(ここでは使っていない模様)。
extract($args);
2行目でフィルターフックwidget_titleを実行して、フォームのtitleのデータを変数$titleに設定します。
$title = apply_filters('widget_title', empty($instance['title']) ?
' ' : $instance['title'], $instance, $this->id_base);
残りの処理でカレンダーを表示します。関数get_calendarは外部の関数でカレンダーデータを取得します(ここでは割愛)。
echo $before_widget;
if ( $title )
echo $before_title . $title . $after_title;
echo '<div id="calendar_wrap">';
get_calendar();
echo '</div>';
echo $after_widget;
$before_widget、$before_title、$after_title、$after_widgetは「WordPress 3のサイドバーにウィジェットを表示するカスタマイズ」の4項にあるregister_sidebarのハッシュキーに相当します。
5.デフォルトウィジェットについて
4項までの説明で、ウィジェットを作るための基本的な仕組みが理解できたと思います。
デフォルトのウィジェットはwp-includes/default-widgets.phpに登録されています。このファイルに書かれている各ウィジェットの処理をトレースしていけば、ウィジェット作成に関する知識をより深めることができるでしょう。
WordPress 3のサイドバーにウィジェットを表示するカスタマイズ
WordPress 3のサイドバーにウィジェットを表示するカスタマイズです。ネタ的にはかなり出遅れてる感じですが、なかなか仕組みが理解できなかったので、WordPressテーマを変更したときの備忘録として残しておきます。
ここでは、ウィジェットが適用されていない2つのサイドバー(sidebar.php/sidebar2.php)にウィジェットを表示する例を説明します。カスタマイズしたいテーマにサイドバーが1つしかない場合、あるいは3つ以上ある場合でも手順はたいして変わりません。
1.sidebar.phpの変更
まず、サイドバー用のテーマファイルsidebar.phpがあるとします。
<ul>
<li><h2>Search this site</h2><?php include (TEMPLATEPATH . '/searchform.php'); ?></li>
<li><h2>Archives</h2>
<ul><?php wp_get_archives('show_post_count=true'); ?></ul>
</li>
<li><h2>Categories</h2>
<ul>
<?php wp_list_cats('sort_column=name&optioncount=1&hide_empty=1&hierarchical=1'); ?>
</ul>
</li>
</ul>
これにウィジェットを表示できるようにするには、一番外側のul要素の開始タグの直後からul要素の終了タグの直前までを以下の2行で括ります。
<?php if ( ! dynamic_sidebar( 'primary-widget-area' ) ) : ?>
…略…
<?php endif; ?>
追加した行にある関数dynamic_sidebarの機能は次の通りです(ここ重要)。
- 「primary-widget-area」というウィジェットエリアにウィジェットが設定されていれば、括っている内容の代わりに、そのウィジェットを表示する。
- 「primary-widget-area」というウィジェットエリアにウィジェットが設定されていなければ、括っている内容をそのまま表示する。
以下に、ウィジェットエリアの状態と、対応するサイドバーの表示内容を示します。厳密には画面はsidebar2.phpのものですが、イメージということで。
ウィジェットエリアにウィジェットが設定されている状態

ウィジェットが設定されているときのサイドバー

ウィジェットエリアにウィジェットが設定されていない状態

ウィジェットが設定されていないときのサイドバー(sidebar.phpの内容を表示)

関数dynamic_sidebarの引数「primary-widget-area」という名称は、ウィジェットを表示する位置を特定するもので、任意の名称で構いません。
変更後のsidebar.phpは次のようになります。追加部分を青色で示しています。
<ul>
<?php if ( ! dynamic_sidebar( 'primary-widget-area' ) ) : ?>
<li><h2>Search this site</h2><?php include (TEMPLATEPATH . '/searchform.php'); ?></li>
<li><h2>Archives</h2>
<ul><?php wp_get_archives('show_post_count=true'); ?></ul>
</li>
<li><h2>Categories</h2>
<ul>
<?php wp_list_cats('sort_column=name&optioncount=1&hide_empty=1&hierarchical=1'); ?>
</ul>
</li>
<?php endif; ?>
</ul>
2.sidebar2.phpの変更
サイドバーが複数ある場合も、同様の設定を行います。1項と異なるのは、関数dynamic_sidebarの引数「primary-widget-area」を「secondary-widget-area」にしている点です。
以下は、もうひとつのサイドバー(sidebar2.php)に設定した例です。
<ul>
<?php if ( ! dynamic_sidebar( 'secondary-widget-area' ) ) : ?>
<li id="calendar"><?php get_calendar(); ?></li>
<li><h2>Recent Entries</h2>
<ul><?php get_archives('postbypost', '10','custom' ,'<li>' ,'</li>'); ?></ul>
</li>
<li><h2>Recent Comments</h2>
<ul><?php get_recently_commented(); ?></ul>
</li>
<li><h2>Recent Trackbacks</h2>
<ul><?php get_recently_trackbacked(); ?></ul>
</li>
<?php endif; ?>
</ul>
つまりサイドバーごとに「primary-widget-area」「secondary-widget-area」の部分の名称を変えれば、いくつでも設定できます。
sidebar.php(sidebar2.php)の設定はこれだ終わりです。
ちなみに、sidebar.phpに記述している中に表示させたいものがあれば、その部分をif文で括らないようにすればOKです。例えば、上のsidebar2.phpでカレンダーだけを常に表示させたい場合は次のようにします。
<ul>
<li id="calendar"><?php get_calendar(); ?></li>
<?php if ( ! dynamic_sidebar( 'secondary-widget-area' ) ) : ?>
<li><h2>Recent Entries</h2>
<ul><?php get_archives('postbypost', '10','custom' ,'<li>' ,'</li>'); ?></ul>
</li>
<li><h2>Recent Comments</h2>
<ul><?php get_recently_commented(); ?></ul>
</li>
<li><h2>Recent Trackbacks</h2>
<ul><?php get_recently_trackbacked(); ?></ul>
</li>
<?php endif; ?>
</ul>
3.ウィジェットエリアの定義(手抜きをしたい場合)
WordPress 3の場合、1項・2項の設定をおこなって「twentyten」テーマの中にあるfunction.phpを自分のテーマディレクトリにコピーすれば、ウィジェット機能はそのまま使えます。
その場合、dynamic_sidebarの引数「primary-widget-area」「secondary-widget-area」の名称は変更しないでください。また、「twentyten」テーマのfunction.phpには、次の4つのウィジェットエリアが用意されています。
- First Footer Widget Area
- Second Footer Widget Area
- Third Footer Widget Area
- Fourth Footer Widget Area
「twentyten」テーマのfunction.phpをそのまま使うと、カスタムメニューやカスタム背景なども同時に使えるかもしれません。
4.ウィジェットエリアの定義(自前で作りたい場合)
自前でウィジェットエリアの定義を作るには、自分のテーマディレクトリ配下に空のfunction.phpを作り、次の内容を設定してください。ここでは当ブログで定義しているもの(ほとんどfunction.phpの流用ですが)からウィジェットに関連する部分のみをそのまま掲載しておきます。
<?php
function koikikukan_widgets_init() {
register_sidebar( array(
'name' => __( 'Primary Widget Area', 'koikikukan3' ),
'id' => 'primary-widget-area',
'description' => __( 'The primary widget area', 'koikikukan3' ),
'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
) );
register_sidebar( array(
'name' => __( 'Secondary Widget Area', 'koikikukan3' ),
'id' => 'secondary-widget-area',
'description' => __( 'The secondary widget area', 'koikikukan3' ),
'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
) );
}
add_action( 'widgets_init', 'koikikukan_widgets_init' );
一番下にあるadd_actionで、ウィジェット管理画面を初期化するフック(widgets_init)を定義し、関数koikikukan_widgets_initを起動します。
add_action( 'widgets_init', 'koikikukan_widgets_init' );
関数koikikukan_widgets_initの中では、関数register_sidebarを2回起動しています。2回起動するのは、サイドバーに追加したdynamic_sidebarに対応させるためです。register_sidebarの引数にあるidの値が1項・2項で定義した「primary-widget-area」「secondary-widget-area」と一致させます。
function koikikukan_widgets_init() {
register_sidebar( array(
…中略…
'id' => 'primary-widget-area',
…中略…
) );
register_sidebar( array(
…中略…
'id' => 'secondary-widget-area',
…中略…
) );
}
関数register_sidebarは、管理画面のウィジェットエリアを作り、そこにドラッグ&ドロップされるウィジェットのテンプレートを定義する機能があります。
register_sidebarの引数に、作りたいウィジェットのスケルトン((X)HTMLマークアップ部分)を定義します。
'name' => __( 'Secondary Widget Area', 'koikikukan3' ),
'id' => 'secondary-widget-area',
'description' => __( 'The secondary widget area', 'koikikukan3' ),
'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
それぞれの意味は次の通りです(公式サイトより)。
- name - サイドバー(ウィジェットエリア)名
- id - サイドバー id
- description - サイドバー(ウィジェットエリア)の説明 (2.9以降)
- before_widget - ウィジェットの前のテキスト
- after_widget - ウィジェットの後のテキスト
- before_title - タイトルの前のテキスト
- after_title - タイトルの後のテキスト
サンプルではサイドバー名の、
'name' => __( 'Secondary Widget Area', 'koikikukan3' ),
はローカライズを行っていますが、次のように直接日本語を書いても構いません。その場合はfunction.phpの文字エンコーディングはUTF-8で保存してください。
'name' => 'ほげほげ',

「カテゴリ」ウィジェットは次のようなマークアップで出力されます。
<li id="categories-2" class="widget-container widget_categories">
<h2 class="widget-title">カテゴリー</h2>
<ul>
<li class="cat-item cat-item-5"><a href="http://.../?cat=5" title="お知らせ に含まれる投稿をすべて表示">お知らせ</a></li>
<li class="cat-item cat-item-7"><a href="http://.../?cat=7" title="イベント に含まれる投稿をすべて表示">イベント</a></li>
<li class="cat-item cat-item-4"><a href="http://.../?cat=4" title="エンタメ に含まれる投稿をすべて表示">エンタメ</a></li>
<li class="cat-item cat-item-36"><a href="http://.../?cat=36" title="ニュース に含まれる投稿をすべて表示">ニュース</a></li>
</ul>
</li>
以上です。これでデフォルトで用意されているウィジェットが利用できるようになります。ウィジェットを自前で作る方法は「WordPress 3でウィジェットを作るカスタマイズ」で紹介します。
WordPressテーマ(WordPress 3.x対応)
当ブログで配布中のWordPressテーマをバージョンアップしてWordPress 3.0対応にしました。
![]()
1.追加機能
WordPress 3.0対応として、以下の機能を追加しました。
- ウィジェットに対応します
- カスタムメニューに対応します
- カスタム背景画像に対応します

ウィジェットはサイドバーのリスト類をドラッグ&ドロップで自由に配置できる機能です。「外観」→「ウィジェット」の画面から直感的に操作できます。
カスタムメニューは、「外観」→「メニュー」の画面から、カテゴリリストの並び順などを任意の順番に変更できたり、他のメニューをリストに加えることができる機能です。作成したカスタムメニューは、先程のウィジェットに「カスタムメニュー」として表示されます。
カスタム背景画像は、「外観」→「背景」の画面から、任意の背景色を選択したり、背景画像をアップロードして適用することができます。下は背景画像を設定したところです。
これだけで背景画像が適用されるようになります。ただしリキッドレイアウトを選択した場合は背景色に「#ffffff」を設定してください。
また、テンプレートの構造を見直し、本文エリアがサイドバーの(X)HTMLマークアップより前方になるようにしました。
2.テーマのダウンロード
下記のページよりテーマをダウンロードしてください。
WordPress テーマ修正
現在配布中の WordPress テーマを修正しました。修正内容は次の1点です。
- 検索時にレイアウトが崩れる不具合を修正
修正されたテーマを利用する場合は、下記のサイトからダウンロードしてください。
修正ファイルは「検索結果 (search.php)」のみです。この部分のみ変更したい方は、以下の内容に入れ替えてください。
<?php get_header(); ?>
<?php
if (preg_match('/layout-three-column-right|layout-three-column-liquid-right/',$layout)) {
} else {
if (preg_match('/three|left/',$layout)) {
?>
<div id="links-left-box">
<div id="links-left">
<?php
include (TEMPLATEPATH . '/sidebar2.php');
?>
</div>
</div>
<?php
}
}
?>
<!-- center -->
<div id="content">
<div class="blog">
<?php if (have_posts()) : ?>
<div class="entry">
<div class="date">Search Results</div>
<div class="navigation">
<div class="alignleft"><?php next_posts_link('« Previous Entries') ?></div>
<div class="alignright"><?php previous_posts_link('Next Entries »') ?></div>
</div>
<?php while (have_posts()) : the_post(); ?>
<h2 class="entry-header"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<p class="entry-footer">Posted at <?php the_time('h:i') ?> | Category: <?php the_category(', ') ?> | <?php edit_post_link('Edit', '', ' | '); ?> <?php comments_popup_link('No Comments', '1 Comment', '% Comments'); ?></p>
<?php endwhile; ?>
<div class="navigation">
<div class="alignleft"><?php next_posts_link('« Previous Entries') ?></div>
<div class="alignright"><?php previous_posts_link('Next Entries »') ?></div>
</div>
</div>
<?php else : ?>
<div class="entry">
<div class="date">Search Results</div>
<div class="entry-header">No posts found. Try a different search?</div>
<?php include (TEMPLATEPATH . '/searchform.php'); ?>
</div>
<?php endif; ?>
</div>
</div>
<?php
if (preg_match('/layout-three-column-right|layout-three-column-liquid-right/',$layout)) {
?>
<div id="links-left-box">
<div id="links-left">
<?php
include (TEMPLATEPATH . '/sidebar2.php');
?>
</div>
</div>
<?php
}
?>
<?php
if (preg_match('/three|right/',$layout)) {
?>
<div id="links-right-box">
<div id="links-right">
<?php
if (preg_match('/two/',$layout)) {
include (TEMPLATEPATH . '/sidebar2.php');
}
get_sidebar();
?>
</div>
</div>
<?php
}
?>
<?php get_footer(); ?>
WordPress テーマのカラムレイアウトを変更する
配布中の WordPress テーマのカラムレイアウトを変更する方法です。
以前、「WordPress テーマ修正(フッタ付きリキッドレイアウト対応)」で変更方法はお知らせしていたのですが、記事が埋もれてしまっている(というか、リンクの張り忘れです)ので、カラムレイアウトの変更方法のみ改めて紹介しておきます。
WordPress テーマは、次のリンクからダウンロードしてください。
1.カラムレイアウトの変更方法
テーマを入れ替えたあと、テーマエディタで「ヘッダー(header.php)」を選択し、下記の赤色部分を変更するだけです。
…前略…
<?php /* <body class="<?php if(is_home()) { ?>layout-two-column-right<?php } else if(is_single()) { ?>layout-one-column<?php } else { ?>layout-two-column-right<?php } ?>"> */ ?>
<?php global $layout; $layout = 'layout-three-column'; ?>
<body class="<?php echo($layout); ?>">
<div id="box" class="clearfix">
…後略…
2.設定値
設定値は次の通りです。
- 3カラム固定(左右サイドバー):layout-three-column
- 3カラムリキッド(左右サイドバー):layout-three-column-liquid
- 3カラムリキッド(右サイドバー):layout-three-column-liquid-right
- 2カラム固定(左サイドバー):layout-two-column-left
- 2カラム固定(右サイドバー):layout-two-column-right
- 2カラムリキッド(右サイドバー):layout-two-column-liquid-right
- 1カラム固定:layout-one-column
- 1カラムリキッド:layout-one-column-liquid
どのような感じになるかは、「WordPress テーマ修正(フッタ付きリキッドレイアウト対応)」をご覧ください。
WordPress 配布テーマのコメントフォームの英語表記を日本語に変更する
現在配布中の WordPress テーマのコメントフォームが英語表記となっているため、これを日本語に変更する方法です。ご質問を頂きましたので本エントリーにて紹介致します。
変更前

変更後

おおざっぱな説明ですいませんが、テーマのコメント(comments.php)を以下の内容に変更してください。日本語変更箇所は青色で示しています。
<?php // Do not delete these lines
if ('comments.php' == basename($_SERVER['SCRIPT_FILENAME']))
die ('Please do not load this page directly. Thanks!');
if (!empty($post->post_password)) { // if there's a password
if ($_COOKIE['wp-postpass_' . COOKIEHASH] != $post->post_password) { // and it doesn't match the cookie
?>
<p class="nocomments">This post is password protected. Enter the password to view comments.<p>
<?php return;
}
}
?>
<div id="comments">
<?php if ('open' == $post->ping_status) : // comment close ?>
<h3 class="comments-head">トラックバックURL</h3>
<input type="text" value="<?php trackback_url(true); ?>" size="60" readonly="readonly" id="trackbackurl" tabindex="1" accesskey="t" onfocus="this.select()" />
<?php endif; ?>
<h3 class="comments-head">コメント & トラックバック<!-- [<?php comments_number('No Responses', 'One Response', '% Responses' );?>]--></h3>
<?php if (!('open' == $post->comment_status) && ('open' == $post->ping_status)) : // comment close ?>
<p class="nocomments">コメントは締め切りました</p>
<?php elseif (('open' == $post->comment_status) && !('open' == $post->ping_status)) : // trackback close ?>
<p class="nocomments">トラックバックは締め切りました</p>
<?php elseif (!('open' == $post->comment_status) && !('open' == $post->ping_status)) : // comment and trackback close ?>
<p class="nocomments">コメント・トラックバックは締め切りました</p>
<?php endif; ?>
<?php if ($comments) : ?>
<div class="commentlist">
<?php foreach ($comments as $comment) : ?>
<div id="comment-<?php comment_ID() ?>" class="comment">
<?php if ($comment->comment_approved == '0') : ?>
<em>あなたの投稿コメントは承認待ちになっています.</em>
<?php endif; ?>
<div class="comment-content"><?php comment_text() ?></div>
<p class="comment-footer">Posted at <a href="#comment-<?php comment_ID() ?>"><?php comment_date('Y.m.j') ?> <?php comment_time() ?></a> by <?php comment_author_link() ?><?php if ( $user_ID ) : ?> | <?php edit_comment_link('edit','',''); ?><?php endif; ?></p>
</div>
<?php endforeach; /* end for each comment */ ?>
</div>
<?php else : // this is displayed if there are no comments so far ?>
<p class="nocomments">コメントはありません</p>
<?php endif; ?>
<?php if (('open' == $post->comment_status) && ('open' == $post->ping_status)) : // open ?>
<p><?php comments_rss_link('コメントフィードを購読する'); ?></p>
<?php endif; ?>
<?php if ('open' == $post->comment_status) : ?>
<h3 class="comments-head">コメント</h3>
<?php if ( get_option('comment_registration') && !$user_ID ) : ?>
<p>You must be <a href="<?php echo get_option('siteurl'); ?>/wp-login.php?redirect_to=<?php the_permalink(); ?>">logged in</a> to post a comment.</p>
<?php else : ?>
<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" name="commentform" id="commentform">
<div id="comments-open-data">
<?php if ( $user_ID ) : ?>
<p><a href="<?php echo get_option('siteurl'); ?>/wp-admin/profile.php"><?php echo $user_identity; ?></a>でログインしています. (<a href="<?php echo get_option('siteurl'); ?>/wp-login.php?action=logout" title="Log out of this account">ログアウト</a>)</p>
<?php else : ?>
<p><label for="author">名前:<?php if ($req) echo "(必須)"; ?></label><br />
<input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="22" tabindex="2" accesskey="n" />
</p>
<p><label for="email">メールアドレス: (公開されません) <?php if ($req) echo "(必須)"; ?></label><br />
<input type="text" name="email" id="email" value="<?php echo $comment_author_email; ?>" size="22" tabindex="3" accesskey="m" />
</p>
<p><label for="url">ウェブサイトURL:</label><br />
<input type="text" name="url" id="url" value="<?php echo $comment_author_url; ?>" size="22" tabindex="4" accesskey="w" />
</p>
<?php endif; ?>
<p><label for="url">コメント本文:</label><br />
<textarea name="comment" id="comment" cols="40" rows="8" tabindex="5" accesskey="c" onfocus="if (this.value == 'Please comment') this.value = '';" onblur="if (this.value == '') this.value = 'Please comment';">コメントしてください</textarea>
</p>
<p>コメント本文に次の(X)HTMLタグを使えます:<br /><?php echo allowed_tags(); ?></p>
<p><input name="submit" type="submit" id="submit" tabindex="6" value="投稿" accesskey="s" />
<input type="hidden" name="comment_post_ID" value="<?php echo $id; ?>" />
</p>
<?php do_action('comment_form', $post->ID); ?>
</div>
</form>
<?php endif; // If registration required and not logged in ?>
<?php endif; // if you delete this the sky will fall on your head ?>
</div><!-- comments -->
WordPress 配布テーマ修正(画像の回り込み対処)
現在配布中の WordPress テーマを修正しました。修正内容は次の2点です。
- 投稿・編集画面で画像の回り込み設定を行なった際に、本文が画像の横に回り込まない不具合を修正
- 回り込み解除のスタイルを追加
修正されたテーマを利用する場合は、下記のサイトからダウンロードしてください。
以下、修正前の問題点および、手動で対処する場合の方法をおしらせします。
1.問題点
投稿・編集画面で、次のように画像を左寄せ(または右寄せ)で挿入し、本文を回り込ませることができます。

ただし、サイトを表示すると、本文の1行目が画像の右下から開始し、2行目以降が画像の下にずれてしまいます。

2.対処方法
手動で対処する場合は下記の修正を行なってください。
まず、スタイルシートに下記の内容を追加します。
p img {
padding: 0;
max-width: 100%;
}
img.aligncenter {
display: block;
margin-left: auto;
margin-right: auto;
}
img.alignright {
padding: 4px;
margin: 0 0 2px 7px;
display: inline;
}
img.alignleft {
padding: 4px;
margin: 0 7px 2px 0;
display: inline;
}
.alignright {
float: right;
}
.alignleft {
float: left;
}
さらに、
- メインインデックス
- アーカイブ
- ページテンプレート
- 単一記事の投稿
のテンプレートにある、
<div class="entry-body">
の部分を、
<div class="entry-body clearfix">
に修正します。
これで次のように適正に本文を回り込ませることができます。

WordPress テーマ修正(フッタ付きリキッドレイアウト対応)
現在配布中の WordPress テーマに、フッタ付きリキッドレイアウトを追加しました。また、カラムレイアウトをこれまでより簡単に切り替えられるように改善しました。
これまで配布していたテーマのリキッドレイアウトは、CSSレイアウトの構造上、背景つきのフッタを表示させると、フッタの表示がサイドバーに重なってしまうという欠点があったため、簡易なテキストのみをフッタとして中央カラムに表示していました。
今回、リキッドレイアウトについては、ネガティブマージンを利用したCSSレイアウトに変更したので、背景つきのフッタもサイドバーに重ならずに表示させることができると思います。
今回追加したリキッドレイアウトは以下の 3 種類です。いずれもフッターを表示します。
3カラムリキッド(左右サイドバー)
![]()
3カラムリキッド(右サイドバー)
![]()
2カラムリキッド(右サイドバー)
![]()
なお、デフォルトはレイアウトは、次の3カラム固定レイアウトです。
![]()
表示は、Windows XP + IE6/Firefox 2/Oprea 9/Safari 3 で確認しています。
テーマのダウンロードおよびテーマの適用方法は、「WordPress テーマ(テンプレート)・3カラム版」を参照してください。以下、各リキッドレイアウトの変更方法を示します(デフォルトレイアウトは3カラム固定レイアウトです)。
1.テーマのダウンロード
下記のリンクよりテーマをダウンロードしてください(後日テンプレート配布ページに移動します)。
2.カラムレイアウト変更方法
テーマエディタで「ヘッダー」を選択し、下記の赤色部分を変更するだけです。
<?php global $layout; $layout = 'layout-three-column'; ?>
設定値は次の通りです。
- 3カラム固定(左右サイドバー):layout-three-column
- 3カラムリキッド(左右サイドバー):layout-three-column-liquid
- 3カラムリキッド(右サイドバー):layout-three-column-liquid-right
- 2カラム固定(左サイドバー):layout-two-column-left
- 2カラム固定(右サイドバー):layout-two-column-right
- 2カラムリキッド(右サイドバー):layout-two-column-liquid-right
- 1カラム固定:layout-one-column
- 1カラムリキッド:layout-one-column-liquid
WordPress の title 要素に表示される「»」を変更・削除する
WordPress の title 要素の表示に wp_title() を使用していると、デフォルトの区切り文字として「»」が表示されます。
この区切り文字を削除・変更する方法について本エントリーにて紹介致します。
なお、配布中の WordPress テーマで、wp_title() を用いているため、記事ページの title 要素の先頭に「»」が表示されてしまいます。ご質問を頂きましたので、後半はこれを削除する方法も併せて紹介します。
1.wp_title() について
wp_title() は表示中の記事タイトルなどを出力するタグです。
- 第1パラメータ:区切り文字
- 第2パラメータ:表示方法
- 第3パラメータ:区切り文字表示位置
第1パラメータ:区切り文字
パラメータを省略すると「»」が区切り文字となります。空の文字列「''」を設定すれば区切り文字は表示されません。
第2パラメータ:表示方法
true を設定すると、記事タイトルなどを echo で出力します。
false を設定すると、記事タイトルなどを関数の返却値として返します。
説明が難しいので、PHP のコードが読める方は下のコードを参照してください。パラメータ $display の処理は関数の最後の方で判定に用いられます。
function wp_title($sep = '»', $display = true, $seplocation = '') {
...ばっさり略...
// Send it out
if ( $display )
echo $title;
else
return $title;
}
第3パラメータ:区切り文字表示位置
パラメータに 'right' を設定すると、記事タイトルなどの右側に表示します。デフォルトでは左側に表示します。
設定例
各パラメータを次のように設定すれば、title 要素を「ブログ記事名 - ブログ名」にできます。
- 第1パラメータ:' - '
- 第2パラメータ:true
- 第3パラメータ:'right'
<title>
<?php if ( is_single() ) { ?><?php wp_title(' - ', true, 'right'); ?>: <?php } ?><?php bloginfo('name'); ?>
</title>

the_title() を使用する
記事ページについては、wp_title() の代わりに the_title() を利用する手もあります。the_title() は区切り文字を表示する代わりに、タイトルの前後に指定した文字列を出力できます。
function the_title($before = '', $after = '', $echo = true) {
$title = get_the_title();
if ( strlen($title) == 0 )
return;
$title = $before . $title . $after;
if ( $echo )
echo $title;
else
return $title;
}
2.配布テーマの変更方法
現状の配布テーマでは、記事ページで次のように先頭に「»」が表示されてしまいます。

これを解消するには「ヘッダー」テンプレートを次の「その1」「その2」いずれかの変更を行ってください。「その1」は wp_title() を、「その2」は the_title() を使用しています。
なお、配布テーマは 2008/10/25 に修正済みです。
変更前
<title>
<?php if ( is_single() ) { ?><?php wp_title(); ?>: <?php } ?><?php bloginfo('name'); ?></title>
変更後(その1)
<title>
<?php if ( is_single() ) { ?><?php wp_title(''); ?>: <?php } ?><?php bloginfo('name'); ?></title>
変更後(その2)
<title>
<?php if ( is_single() ) { ?><?php the_title(); ?>: <?php } ?><?php bloginfo('name'); ?></title>
WordPress テーマ(テンプレート)・3カラム版修正
「WordPress テーマ(テンプレート)・3カラム版」を、久しぶりに修正しました。
変更点は下記の2ヶ所です。
- CSS の float プロパティのクリア方法を変更(一般的なclearfixに変更)
- フッタの WordPress ME へのリンクを WordPress 日本語へのリンクに変更
ダウンロードは「WordPress テーマ(テンプレート)・3カラム版」から行ってください。
3カラムレイアウトで中央カラムを(X)HTMLの最初に記述する(WordPress 用テーマ版)
当サイトで配布中の WordPress 用テーマ(3カラム版)の、固定レイアウトの(X)HTMLマークアップについて、中央カラムをマークアップの前方に移動する方法です。
この内容は、「3カラムレイアウトで中央カラムを(X)HTMLの最初に記述する」を元にしたものです。元記事では WordPress でのテーマ編集方法が分かりにくいため、このエントリーで説明致します。
以下、インデックスを例に、テーマ変更前と変更後の(X)HTMLマークアップ修正内容を示します。この記事のカスタマイズを行う前に、「3カラムレイアウトで中央カラムを(X)HTMLの最初に記述する」で、カラムレイアウトの仕組みを事前に知っておいてください。
1.変更前
まず、赤色で示す include 命令を、<div id="content"> に対応する div 要素の終了タグ直後に移動します(変更後のイメージをご覧ください)。
<?php get_header(); ?>
<?php include (TEMPLATEPATH . '/sidebar2.php'); ?>
<div id="content">
<div class="blog">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="entry" id="post<?php the_ID(); ?>">
<?php the_date('Y.m.d', '<p class="date">', '</p>') ?>
<h2 class="entry-header"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<div class="entry-body">
<?php the_content('Read more »'); ?>
</div>
<p class="entry-footer">Posted at <?php the_time('h:i') ?> | Category: <?php the_category(', ') ?> | <?php comments_popup_link('No Comments', '1 Comment', '% Comments'); ?> <?php edit_post_link('Edit', ' | ', ''); ?></p>
</div>
<?php endwhile; else: ?>
<h2 class="center">Not Found</h2>
<p class="center"><?php _e('Sorry, but you are looking for something that isn\'t here.'); ?></p>
<?php endif; ?>
<p class="content-nav"><?php posts_nav_link(' | ', '« Previous', 'Next »'); ?></p>
</div>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
2.変更後
次に、青色で示す div 要素を追加してください。
<?php get_header(); ?>
<div id="wrap">
<div id="content">
<div class="blog">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="entry" id="post<?php the_ID(); ?>">
<?php the_date('Y.m.d', '<p class="date">', '</p>') ?>
<h2 class="entry-header"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<div class="entry-body">
<?php the_content('Read more »'); ?>
</div>
<p class="entry-footer">Posted at <?php the_time('h:i') ?> | Category: <?php the_category(', ') ?> | <?php comments_popup_link('No Comments', '1 Comment', '% Comments'); ?> <?php edit_post_link('Edit', ' | ', ''); ?></p>
</div>
<?php endwhile; else: ?>
<h2 class="center">Not Found</h2>
<p class="center"><?php _e('Sorry, but you are looking for something that isn\'t here.'); ?></p>
<?php endif; ?>
<p class="content-nav"><?php posts_nav_link(' | ', '« Previous', 'Next »'); ?></p>
</div>
</div>
<?php include (TEMPLATEPATH . '/sidebar2.php'); ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
変更したら「ファイルを更新」をクリックして保存してください。
3.その他のファイル
インデックスと同じ変更を、
- アーカイブ
- ページ
- 検索結果
- シングルポスト
についても行ってください。スタイルシートの変更もお忘れなく。
WordPress テーマ修正
配布中の「WordPress テーマ(テンプレート)・3カラム版」を修正しました。
ダウンロードアーカイブは変更済ですので、上記のリンクよりご利用ください。
変更点は下記の通りです。赤色が削除、青色が追加を示しています。
1.月別アーカイブリストの件数表示
サイドバーの月別アーカイブリストの件数が非表示になっていたので、表示されるように変更しました。
変更前
<li><h2>Archives</h2>
<ul><?php wp_get_archives(); ?></ul>
</li>
変更後
<li><h2>Archives</h2>
<ul><?php wp_get_archives('show_post_count=true'); ?></ul>
</li>
show_post_count=true で件数を表示します。
この変更は下記の記事を参考にさせて頂きました。ありがとうございました。
2.カテゴリーリストの表示変更
カテゴリーリストで、記事数が0のカテゴリーを非表示にしました。また、サブカテゴリーを階層表示するようにしました。
変更前
<li><h2>Categories</h2>
<ul>
<?php wp_list_cats('sort_column=name&optioncount=1&hide_empty=0'); ?>
</ul>
</li>
変更後
<li><h2>Categories</h2>
<ul>
<?php wp_list_cats('sort_column=name&optioncount=1&hide_empty=1&hierarchical=1'); ?>
</ul>
</li>
hide_empty=1 で記事がないカテゴリを非表示にします。
hierarchical=1 でカテゴリーを階層表示します。
この変更は下記の記事を参考にさせて頂きました。ありがとうございました。
また、階層化に伴い、スタイルシートに下記の設定を追加しました。
#links-left ul ul.children,
#links-right ul ul.children {
margin-top: 0;
}
3.ブログロールの表示ページ変更
ブログロールを全てのページで表示されるように変更しました。
変更前
<?php if ( is_home() || is_page() ) { ?>
<?php get_links_list(); ?>
<?php } ?>
変更後
<?php get_links_list(); ?>
WordPress テーマ(テンプレート) XHTML 1.0 Strict
当サイトで配布中の WordPress テーマ(テンプレート)をバージョンアップしました。新しいテンプレートは下記のリンクよりダウンロードしてご利用ください。
注:本テンプレートはデフォルト状態で「最近のコメント」「最近のトラックバック」を表示するようにしています。これらのリストを表示するためには「Commented entry list」プラグインが有効になっている必要があります。
主な変更点は下記の通りです。
1.XHTML 1.0 Strict
これまで配布していたテンプレートのXHTML 1.0 文書型は「XHTML 1.0 Transitional」でしたが、今回「XHTML 1.0 Strict」に変更しました。
XHTML 1.0 Strict では XHTML のお作法が XHTML 1.0 Transitional より少し厳しくなります。例えば引用を示す blockquote 要素では、その直下にインライン要素・テキストを記述するのではなく、ブロックレベル要素(p 要素など)を記述することになります。ブラウザではブロックレベル要素が欠落しても問題なく表示されますが、XHTML 1.0 Strict のお作法に少しずつ慣れていくと良いでしょう(このサイトは XHTML 1.0 Transitional ですが)。
この変更に伴って下記の修正も実施しました。
- form 要素に fieldset 要素追加
- textarea 要素に初期値設定(記事ページ)
2.フォントサイズ変更
やや大きめのフォントサイズにしました。項番5と関連しています。
3.各アーカイブページの title 要素を「記事名+ブログ名」に変更
これまで各アーカイブページの title 要素は「ブログ名+記事(アーカイブ)名」で表示されるようにしていましたが、SEO を考慮して「記事名」が先頭に表示されるよう変更しました。タイトルやアーカイブ名に検索キーワードが含まれていると有利です。
なお、アーカイブページはまだ不具合が残っていますので追って修正したいと思います。
4.float 解除を after 擬似要素に変更
これまで固定レイアウトの float による流し込み解除は br 要素に clear プロパティを与えておりましたが、適切なマークアップではありませんでしたので、after 擬似要素による float 解除に修正しました。
5.フォントサイズを % 指定に変更
px 指定だったため、IE6 での文字サイズ変更が有効にならなかったのですが、% 指定に変更することで有効になります。参考サイトは下記です。ありがとうございました。
また JavaScript によるフォントサイズ変更が多少簡単に設定できるようになります。
この変更により、デフォルトのフォントサイズはこれまでよりかなり大きくなっています。これまでのフォントサイズを再現するには IE6 で「小」にしてください。デフォルトのフォントサイズを変更したい場合は、スタイルシート冒頭の
body {
font-size: 100%;
}
html>body {
font-size: 12pt;
}
の赤色部分を変更してください。他で指定している部分はこの値の相対値として変動します。ちなみにこれまでのテンプレートと近いデフォルト表示をするには、
body {
font-size: 83.3%;
}
html>body {
font-size: 11pt;
}
にしてみてください。
6.line-height の単位を削除
line-height は行間を指定するプロパティです。これまでは % 指定を行っていましたが、このプロパティに単位を与えると、子孫要素のフォントサイズを変更すると、期待する行ボックスにならないとのことです。
良い例が「タグクラウド」で、line-height に単位を与えていると、大きな文字が現われた時、フォントサイズによっては小さな文字に重なり、小さな文字のリンクが有効にならない可能性があります。
参考サイトは下記です。ありがとうございました。
7.pre 要素用 CSS 追加
プログラムコード等を表示する場合を考慮して、pre 要素用の CSS を追加しました。
8.ヘッダの ID 属性値変更
ヘッダの ID 属性値を「banner」から「header」に変更しました。
9.画像用CSS設定削除
本文に画像の挿入を想定して CSS を設定していましたが、左上に表示する場合しか対応していなかったので削除しました。
10.その他
大がかりな変更を行うと、これまでのカスタマイズ記事も大幅に修正しないといけなくなるため、例えばSEO的に有利な、3カラム固定レイアウトで中央カラムを XHTML 文書の先頭にする、というような変更は行っておりません。
また、左右サイドバーのスタイルに対応する links-left / links-right といった属性名も、同様の理由によりそのままの名称にしています(文書構造にデザインを示す単語を用いるのが適切でないことは理解しています)。
中央カラムに「ニュース」「お知らせ」を表示する
公開テンプレートの中央カラムの先頭に「ニュース」「お知らせ」等の、エントリーとは別のちょっとした情報を表示させる方法です。ご質問を頂きましたので本エントリーにて紹介致します。
ここでは Movable Type をサンプルに説明していますが、公開テンプレートであればどれも大体同じカスタマイズで実現可能です。
1.テンプレートの修正
基本は下記のように、テンプレートの中にあるエントリー表示開始位置の少し前に、表示したい情報(青色)を埋め込みます。ここではエントリーと同じスタイルになるようにタイトルと本文を表示しています。
:
<!-- 中央カラム開始 -->
<div id="content">
<div class="blog">
<div class="entry">
<p class="news-header">●お知らせ</p>
<p class="news-content">ブログを始めました。よろしくお願い致します。</p>
</div>
<MTEntries>
<$MTEntryTrackbackData$>
<!-- エントリー日付開始 -->
<MTDateHeader>
<div class="date"><$MTEntryDate format="%x"$></div>
</MTDateHeader>
<!-- エントリー日付終了 -->
:
追加部分全体を div 要素で括り、エントリーと同じ class="entry" を与えています。これで全体のスタイルがエントリーと同じものになります。
その下のタイトルは class="news-header" という新しい class 属性を与え、表示位置を整えています。また本文の p 要素にも class="news-content" を与えています。
2.スタイルシートの修正
下記の内容をスタイルシートに追加します。
.news-header {
margin: 5px 0;
color: #444444;
font-size: 12px;
font-weight: bold;
}
.news-content {
margin-top: 5px;
}
設定は以上です、あとは表示したいタイトルと本文をお好きな内容に書き換えてください。
ただしこの方法では、メインページやアーカイブページに同じ情報を表示したい場合、各テンプレート全てを修正する必要があります。次項ではもう少し変更時の手間が省ける方法を紹介します。
3.テンプレートモジュールにする
お知らせ部分を「テンプレートモジュール」として登録すれば、モジュールの中身を書き換えるだけで、他のテンプレートに同じ内容を反映させることができます。
3.1 新しいテンプレートモジュールの作成
管理メニューより[テンプレート] - [モジュール] - [モジュールを新規作成] の順にクリックし、下記の内容を設定します。
テンプレート名:news
モジュールの内容:下記をコピー
<div class="entry">
<p class="news-header">●お知らせ</p>
<p class="news-content">ブログを始めました。よろしくお願い致します。</p>
</div>
3.2 テンプレートの修正
テンプレートモジュールの内容を表示させたい位置に MTInclude タグを設定します。
:
<!-- 中央カラム開始 -->
<div id="content">
<div class="blog">
<$MTInclude module="news"$>
<MTEntries>
<$MTEntryTrackbackData$>
<!-- エントリー日付開始 -->
<MTDateHeader>
<div class="date"><$MTEntryDate format="%x"$></div>
</MTDateHeader>
<!-- エントリー日付終了 -->
:
スタイルシートは2項の内容をそのままお使いください。
なおこの方法を利用した場合、テンプレートモジュールの内容を変更・保存しただけではメインページや他のアーカイブページに反映されません。
必ず再構築を実施してください。
WordPress テーマ(テンプレート)・3カラム版
WordPress 用のテーマ(テンプレート)・3カラム版を作りました。
![]()
スクリーンショットの3カラム固定レイアウトの他、3カラムリキッドレイアウトや2カラム・1カラムレイアウトなどに変更することも可能です。カラムレイアウトの設定方法につきましては本エントリーを参照ください。
1.利用規定
ご利用の前にテンプレートのページを必ずご覧くださいますよう、よろしくお願い致します。
2.ダウンロード
下のリンクからテーマ(テンプレート)をダウンロードしてください。
2007.02.05 初版
2007.02.06 クレジットバナーにアンカーを追加
2007.02.11 サイドバーのアンカーのない文字への color プロパティ追加
2007.02.24 リキッドレイアウトのサイドバーの垂直開始位置修正
2007.03.13 日付表示のテンプレートタグを変更と、それに伴う5項の JavaScript 削除
2007.07.22 XHTML 1.0 Strict 等、変更
2007.12.03 月別アーカイブリストの件数表示、0件のカテゴリーの非表示等、変更
2008.06.16 floatのクリア方法変更、フッタのWordPress MEへのリンクを変更
2008.10.25 記事ページの title 要素修正
2009.07.07 画像に本文が回り込まない不具合を対処
2010.03.17 検索結果でレイアウトが崩れる不具合を対処
2010.12.07 WordPress 3.0 対応
2011.03.17 ブログのパス変更でバナー画像が表示されなくなる不具合を修正
2011.11.03 v3.0.20「Commented entry listプラグイン」機能を同梱/パンくずリスト表示の不具合を対処/非推奨テンプレートタグの削除/フォントサイズ変更
プラグインのご利用および質問に対する回答等について、ご支援・ご賛同くださる方からの寄付をお待ち申し上げます。
3.テーマの切り替え
ダウンロードしたファイルを展開し、中にある koikikukan3 というフォルダを、wp-content/themes 配下にアップロードしてください。
そのあと、管理画面の「外観」→「テーマ」をクリックすれば、アップロードしたテーマとサムネイルが表示されます(下)。

サムネイルまたは「プレビュー」をクリックすれば、テーマをプレビューできます。「有効化」をクリックすれば即座にテーマが切り替わります。
プレビューの状態からテーマを切り替えるには、プレビュー画面右上の"koikikukanを有効化"をクリックします。

4.カラムレイアウト変更方法
カラムレイアウトを変更するには、テーマエディタで「ヘッダー」を選択し、下記の赤色部分を変更するだけです。
<?php global $layout; $layout = 'layout-three-column'; ?>
各レイアウトの設定値は次の通りです。記事冒頭の画面は「3カラム固定(左右サイドバー)」です。
- 3カラム固定(左右サイドバー):layout-three-column
- 3カラムリキッド(左右サイドバー):layout-three-column-liquid
- 3カラムリキッド(右サイドバー):layout-three-column-liquid-right
- 2カラム固定(左サイドバー):layout-two-column-left
- 2カラム固定(右サイドバー):layout-two-column-right
- 2カラムリキッド(左サイドバー):layout-two-column-liquid-left
- 2カラムリキッド(右サイドバー):layout-two-column-liquid-right
- 1カラム固定:layout-one-column
- 1カラムリキッド:layout-one-column-liquid
以下に切り替えイメージをいくつか示します。
3カラムリキッド(左右サイドバー)
![]()
3カラムリキッド(右サイドバー)
![]()
2カラムリキッド(右サイドバー)
![]()
5.注意事項
サイドバーのリストマークは画像を用いて表示しています。この画像が表示されない場合、アップロードしたテーマの中にある images ディレクトリのパーミッションを変更してください。755 等になっていれば大丈夫と思います。
また、リキッドレイアウトを選択した場合、背景色は必ず「#ffffff」を設定してください。他の色や背景画像を設定していると正常に表示されません。
6.記事の日付表示について
本項目は 2007.03.13 以前にダウンロードされた場合のみ該当します。
本テンプレートでは、タイトル前方に記事の公開日を表示するようにしており、JavaScript を用いてページの前方に同一日付の記事がある場合、日付を重複して表示しないようにしています。なおデフォルトの環境設定でのみ動作確認していますので不具合ございましたらご連絡ください。
この機能を無効にする場合はベースHTMLテンプレート下にある
<script type="text/javascript">
<!--
var elements = document.getElementsByTagName('p');
var work;
var work_old = '';
for (i=0; i<elements.length; i++) {
if (elements[i].getAttribute('class') == 'date' ||
elements[i].getAttribute('className') == 'date') {
work = elements[i].innerHTML;
if(work == work_old){
elements[i].style.display = 'none';
}
work_old = work;
}
}
//-->
</script>
を削除してください。
7.XHTML1.0 Transitional valid
テンプレートを設定した状態で W3C Markup Validation Service での XHTML1.0 Transitional valid および、Another HTML-lint gateway で高得点になるようにしています。
2007.02.06 追記
リストマークが表示されない問題について記述を追加しました。またテーマの右サイドバー下にあるクレジットバナーにリンクが設定されていなかったため、修正しました。
2010.12.07 追記
記事本文をWordPress 3に合わせて全面改訂しました。
2011.01.13
Commented entry listのリンク先を変更しました。
旧:http://hirobee.jp/archives/2005/05/commented-entry-list-11/
新:http://www.koikikukan.com/archives/2011/01/13-005555.php
WordPress テーマ(テンプレート)
WordPress 用のテーマ(テンプレート)を作りました。サンプルのスクリーンショットは2カラム(右サイドバー)ですが、左サイドバーも用意しております。レイアウトの変更方法につきましては本エントリー本文を参照ください。
注:このエントリーに掲載されている内容は古いため、「WordPress テーマ(テンプレート)・3カラム版」をご覧ください。リンク先のテーマで2カラムも利用可能です。
1.動作確認環境
動作確認は下記の環境で行っています。
- OS:Windows2000/XP
- ブラウザ:IE6.0/IE7.0/Firefox 2.0/Opera 9
- WordPress ME:2.0.5~2.0.7(以降のバージョンでもOKのようです)
2.利用規定
ご利用の前にテンプレートのページを必ずご覧くださいますよう、よろしくお願い致します。
3.カラムレイアウト変更方法
このテーマではカラムレイアウトのバリエーションとして、
- 2カラム(右サイドバー:カラム幅固定)
- 2カラム(左サイドバー:カラム幅固定)
- 2カラムリキッドレイアウト(右サイドバー:左カラム幅可変)
- 2カラムリキッドレイアウト(左サイドバー:右カラム幅可変)
の計4種類を用意しています(それぞれのサンプルは下にある画像をご覧ください)。
カラムレイアウトは、HTMLテンプレートの body 要素の class 属性を書き換えることで変更することができます。例えば、2カラムの右サイドバーから2カラム(左サイドバー)に変更したい場合は、header.php の
<body class="layout-two-column-right">
の赤色部分を
<body class="layout-two-column-left">
と、青色の内容に変更します。このテクニックは Designing with Web Standards でも紹介されています。
以下にそれぞれのレイアウトに対する class 属性値を示します。
<body class="layout-two-column-right">
<body class="layout-two-column-liquid-right">
<body class="layout-two-column-left">
<body class="layout-two-column-liquid-left">
配布時は一番上の2カラム・固定レイアウト(右サイドバー)で配布しております。
5.記事の日付表示について
本テンプレートでは、タイトル前方に記事の公開日を表示するようにしており、JavaScript を用いてページの前方に同一日付の記事がある場合、日付を重複して表示しないようにしています。なおデフォルトの環境設定でのみ動作確認していますので不具合ございましたらご連絡ください。
この機能を無効にする場合はベースHTMLテンプレート下にある
<script type="text/javascript">
<!--
var elements = document.getElementsByTagName('p');
var work;
var work_old = '';
for (i=0; i<elements.length; i++) {
if (elements[i].getAttribute('class') == 'date' ||
elements[i].getAttribute('className') == 'date') {
work = elements[i].innerHTML;
if(work == work_old){
elements[i].style.display = 'none';
}
work_old = work;
}
}
//-->
</script>
を削除してください。
6.XHTML1.0 Transitional valid
テンプレートを設定した状態で W3C Markup Validation Service での XHTML1.0 Transitional valid および、Another HTML-lint gateway で高得点になるようにしています。
7.その他
基本的な動作は確認したつもりですが、WordPress の動作を全て理解できていない状態ですので、不具合等ございましたらご連絡ください。
8.ダウンロード
下のリンクからテーマ(テンプレート)をダウンロードしてください。
2007.01.17 初版
2007.01.24 コメントエリアの横幅を修正
2007.02.11 クレジットバナーにアンカーを追加
2007.02.11 サイドバーのアンカーのない文字への color プロパティ追加
2007.02.24 リキッドレイアウトのサイドバーの垂直開始位置修正
テーマの設定方法は、ダウンロードしたファイルを解凍し、中にある koikikukan というフォルダを、wp-content/themes 配下にアップロードしてください。そのあと管理画面の [表示] をクリックすると「利用できるテーマ」にアップロードしたテーマが表示されますので、クリックしてください。
2007.02.04 追記
カラムレイアウト変更内容に誤記がありましたので修正しました。
