You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress自定义首页template-home.php模板如何添加WooCommerce产品分页

WordPress自定义模板WooCommerce产品列表分页实现方案

实现逻辑如下:

  • 原代码中posts_per_page参数值为-1,代表查询所有匹配产品,这是分页不生效的核心原因,需要先修改为你需要的每页展示数量
  • 给查询参数添加paged字段,获取当前分页的页码
  • 在循环结束、重置查询之前添加分页输出代码

修改后的完整代码如下:

<?php
// 获取当前分页页码
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

$product_query = new WP_Query(array(
    'posts_per_page' => 9, // 可自定义每页展示数量,比如3行共9个产品
    'post_type' => 'product',
    'paged' => $paged, // 传入分页参数
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'term_id',
            'terms' => 152,
        )
    )
));

if ($product_query->have_posts()) :

    while ($product_query->have_posts()) : $product_query->the_post();

?>
        <div class="col-lg-4 col-md-4 col-sm-6 col-xs-6 pad_des">
            <div class="item_product_s wow flipInX">
                <a href="<?php the_permalink() ?>">
                    <div class="name_product_s">
                        <h3>
                            <?php the_title() ?>
                        </h3>

                        <p class=" price">
                            <del aria-hidden="true">
                                <span class="woocommerce-Price-amount amount">
                                    <bdi><?php echo get_post_meta(get_the_ID(), '_regular_price', true); ?><span class="woocommerce-Price-currencySymbol">₫</span></bdi>
                                </span>
                            </del>
                            <ins>
                                <span class="woocommerce-Price-amount amount">
                                    <bdi><?php echo get_post_meta(get_the_ID(), '_sale_price', true); ?><span class="woocommerce-Price-currencySymbol">₫</span></bdi>
                                </span>
                            </ins>
                        </p>

                    </div>
                </a>

                <a href="<?php the_permalink() ?>">
                    <div class="zoom_product_s">
                        <?php the_post_thumbnail(); ?>
                    </div>
                </a>
            </div>

        </div>
<?php

    endwhile;

    // 分页输出代码
    echo '<div class="pagination">';
    echo paginate_links( array(
        'total' => $product_query->max_num_pages,
        'current' => $paged,
        'prev_text' => '上一页',
        'next_text' => '下一页',
        'type' => 'list',
    ) );
    echo '</div>';

    wp_reset_postdata();
    wp_reset_query();

endif;

?>

如果需要调整分页的视觉样式,可直接对.pagination类编写对应的CSS规则即可。

内容的提问来源于stack exchange,提问作者Hoàng Năng Hưng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 13:36:03