WordPressによるサイト運営[5] [WordPress]
「トップページをテンプレート化する」
サイトの顔となるトップページをテンプレート化する。下図のように上下2段のウィジェットエリア構成とし、冗談ではテキストウィジェット等を用いた自由な情報の表示、下段はウィジェットの登録が無い場合、最新の投稿を表示する。
①上部のウィジェットエリアを設定
ウィジェットの場所指定に、home-content-widget-upperを使い、wp_widget_num_classを使って、等幅で表示させる。
<?php
if ( is_active_sidebar( 'home-content-widget-upper' ) ) : ?>
<section id="home-widget-area" class="<?php wp_widget_num_class( 'home-content-widget-upper' ); ?>">
<?php dynamic_sidebar( 'home-content-widget-upper' ); ?>
</section>
<?php endif; ?>
②下部のウィジェットエリアの設置とループの組込み
while( have_posts()): と endwhile; でループ処理を組込み最新情報を表示させる。
<section id="update-info">
<?php
if ( ! dynamic_sidebar( 'home-content-widget-lowwer' ) ) :
if ( have_posts() ) :
?><h1 class="update-info-title">information</h1>
<ul>
<?php while ( have_posts() ) : the_post(); ?>
<li><a href="<?php the_permalink(); ?>">
<?php if ( has_post_thumbnail() ) :
the_post_thumbnail();
else :
echo '<img src="' . get_default_image( 'default/update-info-thumbnail-default.png' ) . '" alt="" />';
endif; ?>
</a><h2 class="update-title">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
</h2><p class="update-meta">
<span class="entry-date"><a href="<?php the_permalink(); ?>">
<time datetime="<?php the_time( 'Y-m-d' ); ?>"><?php the_time( get_option( 'date_format' ) ); ?></time>
</a></span>
<span class="entry-category"><?php the_category( ', ' ); ?></span>
</p></li>
<?php endwhile; ?>
</ul><?php endif; /* end if have_posts */
endif; /* end if dynamic_sidebar */ ?></section>
③記事へのリンクを設定
the_parmalinkテンプレートタグでループで表示している記事へのリンクを出力する。
<a href="<?php the_permalink(); ?>">
<img src="img/default/update-info-thumbnail-default.png" alt="">
</a>
④アイキャッチ画像を表示
has_post_thumbnailテンプレートタグでアイキャッチ画像が登録されているか確認し、the_post_thumbnailタグを使用してアイキャッチ(投稿サムネイル)画像を表示する。
<a href="<?php the_permalink(); ?>">
<?php if ( has_post_thumbnail() ) :
the_post_thumbnail();
else :
echo '<img src="' . get_default_image( 'default/update-info-thumbnail-default.png' ) . '" alt="" />';
endif; ?>
</a>
⑤記事タイトルを表示
the_titleタグを使用して記事のタイトルを表示する。
<h2 class="update-title">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
</h2>
⑥公開日を表示
the_timeテンプレートタグで公開日を表示し、get_optionタグで表示フォーマットを指定する。
<p class="update-meta">
<span class="entry-date"><a href="<?php the_permalink(); ?>">
<time datetime="<?php the_time( 'Y-m-d' ); ?>"><?php the_time( get_option( 'date_format' ) ); ?></time>
</a></span>
<span class="entry-category"><?php the_category( ', ' ); ?></span>
</p>
⑦カテゴリーを表示する
the_categoryテンプレートタグで記事の所属するカテゴリーを表示する。
<p class="update-meta">
<span class="entry-date"><a href="<?php the_permalink(); ?>">
<time datetime="<?php the_time( 'Y-m-d' ); ?>"><?php the_time( get_option( 'date_format' ) ); ?></time>
</a></span>
<span class="entry-category"><?php the_category( ', ' ); ?></span>
</p>
⑧トップページの完成
参考資料