
ゼロから作るWP3テーマ vol.2
2010825

WordPressの新テーマ「TwentyTen」のloop.phpの中身をのぞいてみます。
index.phpから呼び出されるloop.phpの中身をのぞいてみます。loop.phpにはトップページやカテゴリーページで記事を表示するための処理が書かれています。
Twenty Tenでは「Asides」または「Gallery」カテゴリーの投稿を別のスタイルで出力するようになっていて、なかでも画像のサムネイルの取り出し方は参考になりました。なのでそのあたりを中心に覚えておきたいソースの書き方を紹介していきます。
前後のページへのリンク
<?php if ( $wp_query->max_num_pages > 1 ) : ?> ・ ・ <?php endif; ?>
このコードで前後のページへのリンクを表示します。
1ページに表示する記事数は「表示設定>1ページに表示する最大投稿数」から変更できますが、この数を超えたぶんはページごとに分けられることになります。
$wp_query->max_num_pagesというのが最大投稿数を表しているようで、1以上でテキストリンクを表示するようになっています。max_num_pagesはドキュメントには説明がないようでwp-includes/query.php内で定義されています。知りたい人はそちらからどうぞ~。
とりあえず、こういうのもあるんだということで覚えるだけにしときます。
カテゴリーごとのスタイル
「Gallery」カテゴリーに属する記事の表示部分をみてみましょう。
カテゴリー判別
<?php if ( in_category( _x('gallery', 'gallery category slug', 'twentyten') ) ) : ?>
カテゴリーが「Gallery」かどうかを判別しています。
ID、クラスの付加
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
このコードを入れておくといくつかのクラスを自動で付加してくれます。
タイトル表示
<h2 class="entry-title"><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
タイトルの表示部分ですね。title属性ではesc_attr__()関数が使われています。ここには記事のタイトルをエスケープし、さらに翻訳が可能なら翻訳した文字列が表示されます。
メタ情報の表示
<?php twentyten_posted_on(); ?>
function.phpで定義されている独自関数です。投稿日時や投稿者名を整形しているようですね。printf()やsprintf()関数なんかはほとんど使ったことがないのですが、自分なりの表示にしたいときの参考になります。
パスワード保護
post_password_required()はパスワードの保護状態を調べる関数です。
使い方は
<?php if ( post_password_required() ) : ?> ・パスワードがかかっているときの処理 <?php else : ?> ・解除されたときの処理 <?php endif; ?>
という感じになります。
サムネイル表示
<?php $images = get_children( array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC', 'numberposts' => 999 ) ); $total_images = count( $images ); $image = array_shift( $images ); $image_img_tag = wp_get_attachment_image( $image->ID, 'thumbnail' ); ?>
get_children()は記事中の画像を取得するのに便利な関数です。
関数リファレンス/get children – WordPress Codex 日本語版
$images は記事に挿入(添付)された画像情報のオブジェクトです。その中身はたとえばこんな感じになります。print_r()で出力してます。
Array (
[25] => stdClass Object
( [ID] => 25
[post_author] => 1
[post_date] => 2010-07-29 20:07:03
[post_date_gmt] => 2010-07-29 11:07:03
[post_content] =>
[post_title] => 20100715_09
[post_excerpt] =>
[post_status] => inherit
[comment_status] => open
[ping_status] => open
[post_password] =>
[post_name] => 20100715_09
[to_ping] =>
[pinged] =>
[post_modified] => 2010-07-29 20:07:03
[post_modified_gmt] => 2010-07-29 11:07:03
[post_content_filtered] =>
[post_parent] => 24
[guid] => http://localhost/wp3/wp-content/uploads/2010/07/20100715_09.jpg
[menu_order] => 0
[post_type] => attachment
[post_mime_type] => image/jpeg
[comment_count] => 0
[filter] => raw
)
)
この中から必要なものを取り出して使います。
$image_img_tag = wp_get_attachment_image( $image->ID, 'thumbnail' );
$wp_get_attachment_image()は画像などの添付ファイルをHTMLとして返す関数です。二番目の引数は画像サイズでthumbnail、medium、largeまたはfullをいれることができます。
























名前:paon