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

如何将指定ID调取的WooCommerce商品设置为2列每列4个的布局

实现WooCommerce指定商品2列布局的方案

你当前代码已经引入Bootstrap栅格系统,优先提供适配Bootstrap的改造方案,也提供无需依赖框架的通用CSS方案。

方案1:Bootstrap适配改造(推荐)

直接替换原有代码即可,修改后会自动排列为2列布局,8个商品刚好每列展示4个:

<div class="col-md-12">
  <div class="row">
  <?php  
  $args = array(
      'post_type'      => 'product',
      'posts_per_page' => 8,
      // 请将数组内的ID替换为你要展示的8个商品ID,当前仅填写了4个
      'post__in' => array(659,662,661,660,xxx,xxx,xxx,xxx),
      'orderby' => 'post__in' // 可选配置:按你填写的ID顺序展示商品,不需要可以删除此行
  );

  $loop = new WP_Query( $args );

  while ( $loop->have_posts() ) : $loop->the_post();
      global $product;
  ?>
    <div class="col-md-6 mb-4"> <!-- mb-4为Bootstrap自带的底部间距类,可自行调整 -->
      <a href="<?php echo get_permalink(); ?>">
        <?php echo woocommerce_get_product_thumbnail(); ?>
      </a>
      <!-- 以下为可选的商品标题、价格输出代码,不需要可以删除 -->
      <h4><a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></h4>
      <?php echo $product->get_price_html(); ?>
    </div>
  <?php
  endwhile;

  wp_reset_postdata(); // 替换原有wp_reset_query,更适配自定义WP_Query场景
  ?>
  </div>
</div>

修改说明:

  • 新增row容器包裹所有商品项,适配Bootstrap栅格规则
  • 每个商品套入col-md-6类,实现每一项占半行宽度,自动排列为2列
  • 移除了原有会破坏布局的<br>换行标签

方案2:通用CSS Grid方案(无Bootstrap也可使用)

如果你的项目没有引入Bootstrap,用CSS Grid也可以快速实现布局:

PHP代码

<div class="custom-product-grid">
<?php  
$args = array(
    'post_type'      => 'product',
    'posts_per_page' => 8,
    'post__in' => array(659,662,661,660,xxx,xxx,xxx,xxx),
    'orderby' => 'post__in'
);

$loop = new WP_Query( $args );

while ( $loop->have_posts() ) : $loop->the_post();
    global $product;
?>
  <div class="product-item">
    <a href="<?php echo get_permalink(); ?>">
      <?php echo woocommerce_get_product_thumbnail(); ?>
    </a>
    <!-- 可选的标题价格代码,不需要可删除 -->
    <h4><a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></h4>
    <?php echo $product->get_price_html(); ?>
  </div>
<?php
endwhile;

wp_reset_postdata();
?>
</div>

CSS代码

将以下代码加入你主题的自定义CSS文件或者外观-自定义-额外CSS中即可:

.custom-product-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px; /* 商品之间的横向、纵向间距,可自行调整数值 */
}
/* 小屏适配:768px宽度以下自动改为1列布局 */
@media (max-width: 767px) {
  .custom-product-grid {
    grid-template-columns: 1fr;
  }
}

内容的提问来源于stack exchange,提问作者Raja Jawad Kiani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 04:27:03