一、最新文章调用
1. 基础最新文章
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => 5,
'orderby' => 'date',
'order' => 'DESC',
'post_status' => 'publish'
);
$latest_posts = new WP_Query($args);
if ($latest_posts->have_posts()) :
while ($latest_posts->have_posts()) : $latest_posts->the_post();
?>
<article>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<div class="post-meta">
<span><?php the_time('Y-m-d'); ?></span>
<span><?php the_category(', '); ?></span>
</div>
<div class="excerpt"><?php the_excerpt(); ?></div>
</article>
<?php
endwhile;
wp_reset_postdata();
else :
echo '<p>暂无文章</p>';
endif;
?>
2. 排除置顶文章的最新文章
<?php
$sticky = get_option('sticky_posts');
$args = array(
'posts_per_page' => 5,
'post__not_in' => $sticky,
'orderby' => 'date',
'order' => 'DESC'
);
$query = new WP_Query($args);
?>
3. 带缩略图的最新文章列表
<?php
$args = array(
'posts_per_page' => 6,
'meta_query' => array(
array(
'key' => '_thumbnail_id',
'compare' => 'EXISTS'
)
)
);
$posts_with_thumb = new WP_Query($args);
if ($posts_with_thumb->have_posts()) :
echo '<div class="latest-posts-grid">';
while ($posts_with_thumb->have_posts()) : $posts_with_thumb->the_post();
?>
<div class="post-item">
<?php if (has_post_thumbnail()) : ?>
<a href="<?php the_permalink(); ?>" class="post-thumb">
<?php the_post_thumbnail('medium', ['alt' => get_the_title()]); ?>
</a>
<?php endif; ?>
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
<span class="post-date"><?php the_time('m/d'); ?></span>
</div>
<?php
endwhile;
echo '</div>';
wp_reset_postdata();
endif;
?>
二、随机文章调用
1. 基础随机文章
<?php
$args = array(
'posts_per_page' => 5,
'orderby' => 'rand',
'post_status' => 'publish',
'ignore_sticky_posts' => 1
);
$random_posts = new WP_Query($args);
if ($random_posts->have_posts()) :
echo '<ul class="random-posts">';
while ($random_posts->have_posts()) : $random_posts->the_post();
?>
<li>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_title(); ?>
</a>
</li>
<?php
endwhile;
echo '</ul>';
wp_reset_postdata();
endif;
?>
2. 随机文章(排除当前文章)
<?php
global $post;
$args = array(
'posts_per_page' => 4,
'orderby' => 'rand',
'post__not_in' => array($post->ID),
'post_status' => 'publish'
);
$random_related = new WP_Query($args);
if ($random_related->have_posts()) :
echo '<div class="related-posts"><h3>相关推荐</h3>';
while ($random_related->have_posts()) : $random_related->the_post();
?>
<div class="related-item">
<?php if (has_post_thumbnail()) : ?>
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('thumbnail'); ?></a>
<?php endif; ?>
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
</div>
<?php
endwhile;
echo '</div>';
wp_reset_postdata();
endif;
?>
3. 带时间的随机文章
<?php
$args = array(
'posts_per_page' => 8,
'orderby' => 'rand',
'date_query' => array(
array(
'after' => '1 year ago'
)
)
);
$recent_random = new WP_Query($args);
?>
三、热门/浏览最多文章
1. 使用 WP-PostViews 插件
<?php
// 需要安装 WP-PostViews 插件
$args = array(
'posts_per_page' => 10,
'orderby' => 'meta_value_num',
'meta_key' => 'views', // WP-PostViews 的字段
'order' => 'DESC',
'post_status' => 'publish'
);
$popular_posts = new WP_Query($args);
if ($popular_posts->have_posts()) :
echo '<ol class="popular-posts">';
$count = 1;
while ($popular_posts->have_posts()) : $popular_posts->the_post();
$views = get_post_meta(get_the_ID(), 'views', true);
?>
<li>
<span class="rank"><?php echo $count++; ?>.</span>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<span class="views">(<?php echo $views ?: 0; ?> 阅读)</span>
</li>
<?php
endwhile;
echo '</ol>';
wp_reset_postdata();
endif;
?>
2. 使用自定义字段统计
<?php
// 首先添加浏览计数功能到 functions.php
function set_post_views() {
if (is_single()) {
$post_id = get_the_ID();
$count = get_post_meta($post_id, 'post_views_count', true);
if ($count == '') {
delete_post_meta($post_id, 'post_views_count');
add_post_meta($post_id, 'post_views_count', 1);
} else {
update_post_meta($post_id, 'post_views_count', $count + 1);
}
}
}
add_action('wp_head', 'set_post_views');
// 然后调用热门文章
$args = array(
'posts_per_page' => 5,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'date_query' => array(
array(
'after' => '30 days ago'
)
)
);
$trending_posts = new WP_Query($args);
?>
3. 周/月热门文章
<?php
function get_weekly_popular_posts($limit = 5) {
global $wpdb;
$week_start = date('Y-m-d H:i:s', strtotime('-7 days'));
$week_end = current_time('mysql');
$query = "
SELECT p.ID, COUNT(c.comment_post_ID) as comment_count
FROM {$wpdb->posts} p
LEFT JOIN {$wpdb->comments} c ON p.ID = c.comment_post_ID
WHERE p.post_type = 'post'
AND p.post_status = 'publish'
AND c.comment_date BETWEEN '{$week_start}' AND '{$week_end}'
GROUP BY p.ID
ORDER BY comment_count DESC
LIMIT {$limit}
";
$results = $wpdb->get_results($query);
$post_ids = wp_list_pluck($results, 'ID');
if (empty($post_ids)) return array();
return get_posts(array(
'post__in' => $post_ids,
'orderby' => 'post__in',
'posts_per_page' => $limit
));
}
// 使用
$weekly_popular = get_weekly_popular_posts(5);
foreach ($weekly_popular as $post) {
setup_postdata($post);
// 输出文章
}
wp_reset_postdata();
?>
四、指定分类文章调用
1. 单分类文章
<?php
$args = array(
'posts_per_page' => 5,
'cat' => 3, // 分类ID
'orderby' => 'date',
'order' => 'DESC'
);
$category_posts = new WP_Query($args);
if ($category_posts->have_posts()) :
echo '<div class="category-posts">';
echo '<h3>' . get_cat_name(3) . '</h3>';
while ($category_posts->have_posts()) : $category_posts->the_post();
?>
<article>
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
<p><?php echo wp_trim_words(get_the_excerpt(), 30, '...'); ?></p>
</article>
<?php
endwhile;
echo '</div>';
wp_reset_postdata();
endif;
?>
2. 多分类文章
<?php
$args = array(
'posts_per_page' => 8,
'category__in' => array(2, 3, 5), // 包含这些分类
'orderby' => 'date',
'order' => 'DESC'
);
// 或者排除某些分类
$args_exclude = array(
'posts_per_page' => 8,
'category__not_in' => array(1, 7), // 排除这些分类
'orderby' => 'date',
'order' => 'DESC'
);
?>
3. 按分类别名调用
<?php
$args = array(
'posts_per_page' => 6,
'category_name' => 'news', // 分类别名
'orderby' => 'date',
'order' => 'DESC'
);
$news_posts = new WP_Query($args);
?>
4. 多级分类文章
<?php
// 获取分类及其子分类的文章
$category_id = 3;
$args = array(
'posts_per_page' => 10,
'cat' => $category_id, // 包含子分类
'orderby' => 'date',
'order' => 'DESC'
);
// 或者只获取子分类
$child_categories = get_categories(array('parent' => $category_id));
$child_ids = wp_list_pluck($child_categories, 'term_id');
$child_args = array(
'category__in' => $child_ids,
'posts_per_page' => 6
);
?>
五、高级组合查询
1. 多种排序条件组合
<?php
$args = array(
'posts_per_page' => 8,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => '_thumbnail_id',
'compare' => 'EXISTS'
),
array(
'key' => 'post_views_count',
'value' => 100,
'compare' => '>',
'type' => 'NUMERIC'
)
),
'orderby' => array(
'meta_value_num' => 'DESC', // 按浏览量
'date' => 'DESC' // 再按日期
),
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => array(2, 3),
'operator' => 'IN'
)
)
);
$advanced_posts = new WP_Query($args);
?>
2. 分页支持
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'posts_per_page' => 10,
'paged' => $paged,
'orderby' => 'date',
'order' => 'DESC'
);
$paged_posts = new WP_Query($args);
if ($paged_posts->have_posts()) :
while ($paged_posts->have_posts()) : $paged_posts->the_post();
// 文章内容
endwhile;
// 分页导航
echo '<div class="pagination">';
echo paginate_links(array(
'total' => $paged_posts->max_num_pages,
'current' => $paged,
'prev_text' => '«',
'next_text' => '»'
));
echo '</div>';
wp_reset_postdata();
endif;
?>
六、实用函数封装
1. 通用文章查询函数
/**
* 获取文章列表
* @param array $args 查询参数
* @param string $template 模板类型 (list/grid)
* @return string HTML
*/
function get_posts_list($args = array(), $template = 'list') {
$defaults = array(
'posts_per_page' => 5,
'orderby' => 'date',
'order' => 'DESC',
'post_status' => 'publish'
);
$args = wp_parse_args($args, $defaults);
$query = new WP_Query($args);
if (!$query->have_posts()) {
return '<p>暂无文章</p>';
}
ob_start();
if ($template == 'grid') {
echo '<div class="posts-grid">';
while ($query->have_posts()) : $query->the_post();
get_template_part('template-parts/content', 'grid');
endwhile;
echo '</div>';
} else {
echo '<ul class="posts-list">';
while ($query->have_posts()) : $query->have_posts();
$query->the_post();
?>
<li>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_title(); ?>
</a>
<span class="post-date"><?php the_time('Y-m-d'); ?></span>
</li>
<?php
endwhile;
echo '</ul>';
}
wp_reset_postdata();
return ob_get_clean();
}
// 使用示例
echo get_posts_list(array('cat' => 3, 'posts_per_page' => 6), 'grid');
2. 小工具类
class Recent_Posts_Widget extends WP_Widget {
public function __construct() {
parent::__construct(
'recent_posts_widget',
'最新文章',
array('description' => '显示最新文章列表')
);
}
public function widget($args, $instance) {
$title = !empty($instance['title']) ? $instance['title'] : '最新文章';
$number = !empty($instance['number']) ? $instance['number'] : 5;
echo $args['before_widget'];
echo $args['before_title'] . esc_html($title) . $args['after_title'];
$query_args = array(
'posts_per_page' => $number,
'orderby' => 'date',
'order' => 'DESC',
'ignore_sticky_posts' => 1
);
$recent_posts = new WP_Query($query_args);
if ($recent_posts->have_posts()) {
echo '<ul>';
while ($recent_posts->have_posts()) {
$recent_posts->the_post();
echo '<li>';
echo '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
echo '<span class="post-date">' . get_the_date('m-d') . '</span>';
echo '</li>';
}
echo '</ul>';
} else {
echo '<p>暂无文章</p>';
}
wp_reset_postdata();
echo $args['after_widget'];
}
public function form($instance) {
$title = !empty($instance['title']) ? $instance['title'] : '最新文章';
$number = !empty($instance['number']) ? $instance['number'] : 5;
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>">标题:</label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>"
name="<?php echo $this->get_field_name('title'); ?>"
type="text" value="<?php echo esc_attr($title); ?>">
</p>
<p>
<label for="<?php echo $this->get_field_id('number'); ?>">显示数量:</label>
<input id="<?php echo $this->get_field_id('number'); ?>"
name="<?php echo $this->get_field_name('number'); ?>"
type="number" min="1" max="20"
value="<?php echo esc_attr($number); ?>">
</p>
<?php
}
}
// 注册小工具
add_action('widgets_init', function() {
register_widget('Recent_Posts_Widget');
});
七、性能优化技巧
1. 使用 transients 缓存
function get_cached_popular_posts($limit = 5, $expire = 3600) {
$cache_key = 'popular_posts_' . $limit;
$posts = get_transient($cache_key);
if (false === $posts) {
$args = array(
'posts_per_page' => $limit,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC'
);
$query = new WP_Query($args);
$posts = $query->posts;
set_transient($cache_key, $posts, $expire);
}
return $posts;
}
2. 限制查询字段
$args = array(
'posts_per_page' => 10,
'fields' => 'ids' // 只获取ID,提高性能
);
$post_ids = get_posts($args);
foreach ($post_ids as $post_id) {
// 根据需要单独获取字段
$title = get_the_title($post_id);
$link = get_permalink($post_id);
}
3. 使用 no_found_rows
$args = array(
'posts_per_page' => 5,
'no_found_rows' => true, // 不分页时使用,提高性能
'update_post_meta_cache' => false,
'update_post_term_cache' => false
);
八、常用参数速查表
| 参数 | 说明 | 示例值 |
|---|---|---|
posts_per_page | 显示数量 | 5, -1(全部) |
orderby | 排序方式 | date, rand, title, comment_count, meta_value |
order | 排序方向 | DESC, ASC |
cat | 分类ID | 3, '3,5,7' |
category_name | 分类别名 | 'news' |
category__in | 包含分类 | array(2,3) |
category__not_in | 排除分类 | array(1,4) |
tag | 标签 | 'wordpress' |
tag_id | 标签ID | 7 |
author | 作者ID | 1 |
meta_key | 自定义字段名 | 'views' |
meta_value | 自定义字段值 | '100' |
post__in | 指定文章ID | array(1,3,5) |
post__not_in | 排除文章ID | array(2,4) |
post_type | 文章类型 | 'post', 'page', 'custom' |
post_status | 文章状态 | 'publish', 'draft' |
paged | 分页 | $paged |
offset | 偏移量 | 5 |
date_query | 日期查询 | array('after' => '1 month ago') |
tax_query | 分类法查询 | 多维数组 |
meta_query | 自定义字段查询 | 多维数组 |
ignore_sticky_posts | 忽略置顶 | 1 |
has_password | 密码保护 | false |
九、最佳实践建议
- 重置查询:使用
wp_reset_postdata()重置全局$post - 性能考虑:大量查询时使用
'no_found_rows' => true - 缓存优化:热门查询使用 transients 缓存
- 安全过滤:用户输入参数使用
intval()或sanitize_text_field() - 错误处理:检查查询结果是否存在
- SEO优化:为链接添加
title属性 - 响应式设计:使用合适的图片尺寸
- 懒加载:图片使用
loading="lazy"属性
将这些代码片段保存为单独的 PHP 文件或在主题的 functions.php中使用,可以大大提高 WordPress 开发效率。


湘公网安备43020002000238