wordpress调用指定ID分类下的最新、热门、评论内容
wordpress 2025-08-02 18
在WordPress中,要调用指定分类ID下的:
最新文章
最多阅读(需要配合阅读量插件或自定义字段)
最新评论的文章
可以分别用WP_Query、get_posts、get_comments等实现。以下是无插件、可复用的代码片段,适合写在主题的functions.php或自定义插件中,并通过短代码或模板调用。
1.获取指定分类下的最新文章
function get_latest_posts_by_cat($cat_id = 1, $limit = 5) {
$args = array(
'cat' => $cat_id,
'posts_per_page' => $limit,
'orderby' => 'date',
'order' => 'DESC',
'post_status' => 'publish',
);
$query = new WP_Query($args);
if ($query->have_posts()):
echo '<ul>';
while ($query->have_posts()): $query->the_post();
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
endwhile;
echo '</ul>';
wp_reset_postdata();
endif;
}
调用方法
<?php get_latest_posts_by_cat(3, 5); ?>
2.获取指定分类下最多阅读的文章
WordPress默认不记录阅读量,需配合插件(如PostViewsCounter)或自定义字段(如post_views_count)
假设你使用的是自定义字段post_views_count:
function get_most_viewed_posts_by_cat($cat_id = 1, $limit = 5) {
$args = array(
'cat' => $cat_id,
'posts_per_page' => $limit,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'post_status' => 'publish',
);
$query = new WP_Query($args);
if ($query->have_posts()):
echo '<ul>';
while ($query->have_posts()): $query->the_post();
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
endwhile;
echo '</ul>';
wp_reset_postdata();
endif;
}
调用方法
<?php get_most_viewed_posts_by_cat(3, 5); ?>
3.获取指定分类下最新评论的文章
获取最新评论,并按评论时间排序,返回对应文章列表。
function get_recent_commented_posts_by_cat($cat_id = 1, $limit = 5) {
global $wpdb;
$sql = "
SELECT DISTINCT {$wpdb->posts}.ID, {$wpdb->posts}.post_title, {$wpdb->posts}.post_date, {$wpdb->comments}.comment_date
FROM {$wpdb->posts}
INNER JOIN {$wpdb->comments} ON {$wpdb->posts}.ID = {$wpdb->comments}.comment_post_ID
WHERE {$wpdb->posts}.post_status = 'publish'
AND {$wpdb->posts}.post_type = 'post'
AND {$wpdb->posts}.ID IN (
SELECT object_id FROM {$wpdb->term_relationships}
WHERE term_taxonomy_id = %d
)
ORDER BY {$wpdb->comments}.comment_date DESC
LIMIT %d
";
$results = $wpdb->get_results($wpdb->prepare($sql, $cat_id, $limit));
if ($results) {
echo '<ul>';
foreach ($results as $post) {
echo '<li><a href="' . get_permalink($post->ID) . '">' . esc_html($post->post_title) . '</a></li>';
}
echo '</ul>';
}
}
调用方法
<?php get_recent_commented_posts_by_cat(3, 5); ?>
调用内容 | 函数名 | 示例调用(分类 ID = 3) |
---|---|---|
最新文章 | get_latest_posts_by_cat() | <?php get_latest_posts_by_cat(3, 5); ?> |
最多阅读 | get_most_viewed_posts_by_cat() | <?php get_most_viewed_posts_by_cat(3, 5); ?> |
最新评论文章 | get_recent_commented_posts_by_cat() | <?php get_recent_commented_posts_by_cat(3, 5); ?> |
以上代码可以直接在模板文件中调用,也可以封装为短代码在Gutenberg区块编辑器中直接使用。