the_dateを1ページに2つ以上使う場合の問題と対策 : WordPress

Pocket

追記 2011.09.11 the_dateではなくthe_timeを使う。詳しくは下記を参照。
» the_timeとthe_date : WordPress

同一ページ内に2のカテゴリーのタイトル・パーマリンク・日付の一覧を表示する。query_postsを使ったループ処理を2個記述することでタイトル・パーマリンクは取得できた。
日付の取得はthe_dateを用いていたが2つめのループでは日付を取得できなかった。

th_timeにを使うことで表示できた。
» WordPress › Support » the_date() is not appearing on my posts.

下記のコードでは2個目のループのthe_dateでは日付を取得できない。

<h2>foo</h2>
<ul>
<?php query_posts($query_string . '&category_name=foo&showposts=5'); ?>
<?php if(have_posts()):while(have_posts()):the_post();?>
    <li><?php the_date("Y年m月d日"); ?>&emsp;<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; ?>
</ul>
<h2>bar</h2>
<ul>
<?php query_posts($query_string . '&category_name=bar&showposts=5'); ?>
<?php if(have_posts()):while(have_posts()):the_post();?>
    <li><?php the_date("Y年m月d日"); ?>&emsp;<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; ?>
</ul>

the_dateをthe_timeに変えるとうまくいく。

<h2>hoo</h2>
<ul>
<?php query_posts($query_string . '&category_name=hoo&showposts=5'); ?>
<?php if(have_posts()):while(have_posts()):the_post();?>
    <li><?php the_time("Y年m月d日"); ?>&emsp;<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; ?>
</ul>

<h2>bar</h2>
<ul>
<?php query_posts($query_string . '&category_name=bar&showposts=5'); ?>
<?php if(have_posts()):while(have_posts()):the_post();?>
    <li><?php the_time("Y年m月d日"); ?>&emsp;<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; ?>
</ul>

この場合the_dateではなくthe_timeを使うのが正しいと思うけれど2個目のループ用にWP_Queryオブジェクトを作成してthe_dateを使ってもうまくいったのでメモ。

<h2>foo</h2>
<ul>
<?php query_posts($query_string . '&category_name=foo&showposts=5'); ?>
<?php if(have_posts()):while(have_posts()):the_post();?>
    <li><?php the_date("Y年m月d日"); ?>&emsp;<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; ?>
</ul>

<h2>bar</h2>
<?php
    $myQuery = new WP_Query();
    $param = array(
        'category_name' => 'bar',
        'posts_per_page' => '5',
        'post_type' => 'post',
        'post_status' => 'publish',
        'orderby' => 'date',
        'order' => 'DESC'
    );
    $myQuery->query($param);
?>
<?php if($myQuery->have_posts()): while($myQuery->have_posts()) : $myQuery->the_post(); ?>
    <p><?php the_date("Y年m月d日"); ?>&emsp;<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
<?php endwhile;endif; ?>

コメント

No comments yet.

コメントの投稿

改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。