これまで指定カテゴリの記事一覧はこんなコードで表示してました。
<div> <h2><a href="<?php echo get_category_link('1'); ?>"><?php echo get_the_category_by_ID('1') ?></a></h2> <dl> <?php $lastposts = get_posts('category=1&numberposts=5'); foreach($lastposts as $post) : setup_postdata($post); ?> <dt><?php the_time('Y/n/j'); ?></dt> <dd><a href="<?php the_permalink(); ?>"><?php the_title_attribute(); ?></a></dd> <?php endforeach; ?> </dl> </div>
これだと、該当カテゴリに記事が無い場合は何も表示されず素っ気ない感じがします。
そこで、記事がない場合に「ごめんね」コピーを表示します。
ついでにタイトルクリックで一覧ページにジャンプの仕様を、一覧ボタン表示に変え、これも記事が無い場合は表示しないようにします。
その改良版コードがこれ。
大したカスタマイズじゃないですけど…メモメモ。
<?php $lastposts = get_posts('category=1&numberposts=5'); ?> <div class="topnews"> <div?class="cat-title"> <h2><?php echo get_the_category_by_ID('1') ?></h2> <?php if($lastposts): ?> <a href="<?php echo get_category_link('1'); ?>"?class="bt-catidx">一覧はこちら</a> <?php endif; ?> </div> <?php if($lastposts): ?> <dl> <?php foreach($lastposts as $post) : setup_postdata($post); ?> <dt><?php the_time('Y/n/j'); ?></dt> <dd><a href="<?php the_permalink(); ?>"><?php the_title_attribute(); ?></a></dd> <?php endforeach; ?> </dl> <?php else : ?> <p>ただいま準備中です。</p> <?php endif; ?> </div>
追記:カテゴリーIDの指定が・・・
上記例だとカテゴリーIDの指定が何度も必要で面倒ミスの元になりそう!
エクスポート→インポートでIDが変わったりすることもあるし。
というわけで、カテゴリースラッグからIDを取得してゴニョることにしました。
<?php $lastposts = get_posts('category=1&numberposts=5'); ?> <div> <div?class="cat-title"> <h2><?php echo get_the_category_by_ID('1') ?></h2> <?php if($lastposts): ?> <a href="<?php echo get_category_link('1'); ?>"?class="bt-catidx">一覧はこちら</a>
これを
<?php $term_id = get_category_by_slug('xxxxx')->term_id; $lastposts = get_posts('category='.$term_id.'&numberposts=5'); ?> <div> <div?class="cat-title"> <h2><?php echo get_the_category_by_ID($term_id) ?></h2> <?php if($lastposts): ?> <a href="<?php echo get_category_link($term_id); ?>"?class="bt-catidx">一覧はこちら</a>
こう。