在百度知道有知友提出这样的问题:
wordpress程序,怎样可以获取当前文章分类下的所有文章
根据这个问题可以整理出的思路:
- 1、利用get_the_ID()函数获取当前文章的ID
- 2、自定义函数,并根据文章ID获取其所在的全部分类ID
- 3、根据文章ID、分类ID,重构query
据此思路,提供代码如下:
if ( ! function_exists('wpdit_get_posts_in_same_categories') ) {
function wpdit_get_posts_in_same_categories( $post_id = 0 ){
// 验证文章ID
$post = get_post( $post_id );
if ( ! $post )
return;
// 获取文章所属分类
$categories = get_the_category($post_id);
if ( ! count( $categories ) )
return;
$cid = array();
foreach ( $categories as $key => $category ) {
$cid[] = $category->term_id;
}
// 重构query
$args = array(
'post__not_in' => array( $post_id ),
'category__in' => $cid,
'posts_per_page' => 10 // 每页显示数量,-1表示获取全部,但不建议
);
$relate_posts = get_posts( $args );
if ( is_wp_error($relate_posts) )
return;
// 输出
foreach ($relate_posts as $key => $relate_post ) {
printf( '%s',
get_permalink( $relate_post->ID ),
get_the_title( $relate_post->ID )
);
}
}
}
调用方法:
$post_id = get_the_ID(); //必须位于循环内,否则get_the_ID()无结果 wpdit_get_posts_in_same_categories( $post_id );
将该调用方法放置到需要的地方,只要指定post_id即可。
客官,动手试试吧~~~
建议同步阅读:
几招搞定wordpress自由获取指定分类中的日志
路过~混个脸熟。
欢迎常来~