wordpress 首页调用新闻或产品数量修改

一、修改主查询数量(推荐方法)

1.1 使用 pre_get_posts 钩子

这是最专业和高效的方式,直接修改主查询对象而不需要额外的查询:

// 在主题的 functions.php 文件中添加
function custom_homepage_query($query) {
// 只在首页且是主查询时修改
if ($query->is_home() && $query->is_main_query()) {
// 修改新闻/博客文章数量
$query->set('posts_per_page', 6); // 显示6篇文章

// 如果要修改特定文章类型(如产品)
// $query->set('post_type', 'product');
// $query->set('posts_per_page', 8); // 显示8个产品
}
}
add_action('pre_get_posts', 'custom_homepage_query');

1.2 针对不同设备设置不同数量

function responsive_home_query($query) {
if ($query->is_home() && $query->is_main_query()) {
// 检测移动设备
if (wp_is_mobile()) {
$query->set('posts_per_page', 4); // 移动端显示4篇
} else {
$query->set('posts_per_page', 8); // 桌面端显示8篇
}
}
}
add_action('pre_get_posts', 'responsive_home_query');

二、修改特定文章类型的数量

2.1 自定义文章类型(如产品)数量控制

function custom_product_query($query) {
// 只在首页且查询产品类型时
if ($query->is_home() && $query->is_main_query() && $query->get('post_type') == 'product') {
$query->set('posts_per_page', 12); // 首页显示12个产品
}
}
add_action('pre_get_posts', 'custom_product_query');

2.2 使用 WP_Query 创建自定义查询

如果首页有专门的产品展示区块:

// 在模板文件(如 front-page.php 或 home.php)中
$products = new WP_Query([
'post_type' => 'product', // WooCommerce产品
'posts_per_page' => 6, // 显示6个产品
'orderby' => 'date', // 按日期排序
'order' => 'DESC' // 降序排列
]);

if ($products->have_posts()) :
while ($products->have_posts()) : $products->the_post();
// 产品显示代码
the_title();
endwhile;
wp_reset_postdata();
endif;

通过以上方法,可以灵活控制WordPress首页显示的各种内容数量。推荐使用pre_get_posts方法修改主查询,这是最符合WordPress主题标准且性能最佳的方式。对于特殊需求,可以创建自定义查询或使用插件辅助实现。

我爱主题网 自2012
主题:260+ 销售:1000+
兼容浏览器

电话咨询

7*12服务咨询电话:

1855-626-3292

微信咨询