【WordPress】現在の投稿のカテゴリに属する投稿一覧を取得して表示
今回はコードだけ紹介します。ショートコードで関数を呼び出します。
function list_post( $args ){
global $post;
$my_category = get_the_category( $post->ID );
$defaults = array(
'posts_per_page' => 5,
);
$atts = shortcode_atts( $defaults , $args , 'list_posts' );
if( is_single() ){
$post_args = array(
'posts_per_page' => $atts[ 'posts_per_page' ],
'category_name' => $my_category[0]->slug,
);
$my_posts = get_posts( $post_args );
echo '<ul>';
foreach( $my_posts as $post ){
setup_postdata( $post );
$output = '<li>' . get_the_title() . '</li>';
echo $output;
}
wp_reset_postdata();
echo '</ul>';
}
}
add_shortcode( 'list_posts' , 'list_post' );
デフォルトでは5件取得するようになってますが、引数で調節可能。
デフォルト:[list_posts]
3件取得:[list_posts posts_per_page="3″]
ディスカッション
コメント一覧
まだ、コメントがありません