WordPressの投稿日と記事タイトルを反映させてお知らせ欄を作ろう!【html→php】

こんにちは!ちづみ(@098ra0209)です!私は今カンボジアにいながらこの記事を書いています。ノマドワーカーです!

今回はhtml、cssファイルをWordPressに導入した時に、投稿の日付、タイトルをphpで出力する方法をまとめています。

ちづみ
要するに
ちづみ
html、cssで作ったこの部分を↓
ちづみ
WordPressの投稿記事の日付とタイトルに反映されるように作っていくよ!

 

ちづみ
ゴールはこうなります!

 

 

 

html

 

<section id="news">
<div class="inner">

<p class="lead">お知らせ</p>

<ul class="news-list">
  <li><time>2018/01/01</time>テキストテキストテキストテキストテキストテキストテキスト</li>
	<li><time>2018/01/01</time>テキストテキストテキストテキストテキストテキストテキストトテキストテキスト</li>
	<li><time>2018/01/01</time>テキストテキストテキストテキストテキストテキストテキスト</li>
	<li><time>2018/01/01</time>テキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキスト</li>
	<li><time>2018/01/01</time>テキストテキストテキストテキストテキストテキストテキスト</li>
</ul>

</div>
</section>

 

 

css

 

.news-list {
	list-style: none;
	margin: 0;
	padding: 0;
}

.news-list li {
	border-top: 1px solid #ccc;
	padding: 12px 24px 12px 236px;
	position: relative;
}

.news-list li:last-child {
	border-bottom: 1px solid #ccc;
}

.news-list time {
	color: #b4cf9e;
	font-weight: 700;
	left: 100px;
	position: absolute;
	top: 12px;
}

.news-list a {
    color: #333;
}

 

php

 

<?php
	            $args = array(
	                'post_type' => 'post', /* 投稿タイプ */
	                'paged' => $paged,
	                'order' => 'DESC',
	                'posts_per_page' => 5
	            );
	            query_posts( $args );
	            if (have_posts()) :
	                while (have_posts()) : the_post();
	            ?>
	
	<?php
	            endwhile;
	            endif;
	            ?>

これを導入します。簡単に言うと、ページの投稿タイプをループで表示してねと言うことです。

あとは日付、記事タイトル部分にテンプレートタブを埋め込みましょう。

 

WordPressのテンプレートタグ

 

記事の投稿日

<?php the_time('Y/n/j'); ?>

 

記事のタイトル

<?php the_title(); ?>

 

タイトルをクリックすると記事に飛ぶようにする

今回は記事のタイトル部分をリンクにしてタイトルをクリックすると記事に飛ぶようにしたいので、その場合はリストをこう作ります。

<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>

 

これでクリックすると記事ページに飛ぶようになります。

これを踏まえ、記事の日付、タイトルを埋め込んだコードがこちらです。

<li><time datetime="2018-01-01"><?php the_time('Y/n/j'); ?></time><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>

 

こちらを先ほどのphpのループの中に入れます。

 

こうなります。

<section id="news">
<div class="inner">

<p class="lead">お知らせ</p>


<ul class="news-list">
	<?php
	            $args = array(
	                'post_type' => 'post', /* 投稿タイプ */
	                'paged' => $paged,
	                'order' => 'DESC',
	                'posts_per_page' => 5
	            );
	            query_posts( $args );
	            if (have_posts()) :
	                while (have_posts()) : the_post();
	            ?>
	<li><time><?php the_time('Y/n/j'); ?></time><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
	<?php
	            endwhile;
	            endif;
	            ?>

	
</ul>

</div><!-- /inner -->
</section><!-- /news -->