カテゴリー内の記事リストを表示することは、トップページの新着記事とかサイドバーとか、使う機会がが多いです。
特定のカテゴリーの記事一覧を表示
カテゴリーID 5の記事を10件表示する
get_postsで取得
$args = array(
'posts_per_page'=> 10,
'category'=> 5
);
$myposts = get_posts( $args );
if( ! empty( $myposts ) ){
$html = '<ul>';
foreach ( $myposts as $post ){
$html .= '<li><a href="' . get_permalink( $post->ID ) . '">'
. $post->post_title . '</a></li>';
}
$html .= '<ul>';
}
[解決済み] [閉] 特定のカテゴリーの記事一覧を表示したい。 (6 件の投稿)
http://ja.forums.wordpress.org/topic/154?replies=6
あらかじめ表示させたいカテゴリが決まっている場合はこれでOKですね。
でも、今後増えるカテゴリーについても自動で表示させたい場合は、ちょっとこれだと難しいです。
カテゴリ毎の記事一覧を表示
カテゴリが増えても表示させる
<?php
$categories = get_categories();
foreach($categories as $category):
?>
<h2><a href="<?php echo esc_url(get_category_link($category->term_id)); ?>"><?php echo $category->name; ?></a></h2>
<?php
$args = array(
'cat' => $category->term_id,
'posts_per_page' => 10,
));
$the_query = new WP_Query($args);
if ($the_query->have_posts()):
?>
<ul>
<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
<li><a href="<?php echo get_permalink( $post->ID ); ?>"><?php echo $post->post_title; ?></a></li>
<?php endwhile; ?>
</ul>
<?php wp_reset_postdata(); ?>
<?php else: ?>
<p>投稿はありません。</p>
<?php endif; ?>
<?php endforeach; ?>
特定カテゴリの記事リストのショートコードを作成してウィジェットに設置
特定のカテゴリーに属する記事、最新5件をサイドバーウィジェットに表示したい時。
if ( ! function_exists( 'dis_catposts_func' ) ){
function disp_catposts_func($atts) {
$args = array(
'category_name'=> array('news','items'),
'post_status' => 'publish',
'posts_per_page' => 5,
'orderby' => 'desc'
);
$the_query = new WP_Query($args);
$html = '';
if($the_query->have_posts()):
$html = '<ul class="categ-recent-posts">';
while($the_query->have_posts()):
$the_query->the_post();
$post_image = get_the_post_thumbnail( $post->ID, 'thumbnail', array( 'class' => 'categ-ph' ) );
$html .= '<li>
<a href="' . get_permalink( $post->ID ) . '" >' . $post_image . '</a><br>'
. get_the_title( $post->ID ) . '</a>
</li>';
endwhile;
wp_reset_postdata();
$html .= '</ul>';
endif;
return $html;
}
add_shortcode( 'disp_catposts', 'disp_catposts_func' );
}
ウィジェットでショートコードを使うには以下のコードをfunctions.phpに記載するのを忘れずに。
//ウィジェットでショートコードを使えるようにする
add_filter('widget_text', 'do_shortcode' );
関数リファレンス/WP Query
http://wpdocs.osdn.jp/%E9%96%A2%E6%95%B0%E3%83%AA%E3%83%95%E3%82%A1%E3%83%AC%E3%83%B3%E3%82%B9/WP_Query
テンプレートタグ/get posts
http://wpdocs.osdn.jp/%E3%83%86%E3%83%B3%E3%83%97%E3%83%AC%E3%83%BC%E3%83%88%E3%82%BF%E3%82%B0/get_posts