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

如何将WooCommerce foreach循环结果存入数组适配主题滑块函数?

解决方案

核心思路

你不需要通过foreach循环输出产品再存数组,直接利用你已经有的$products数组(就是foreach里遍历的那个源数组),把它传给滑块函数即可。如果主题滑块函数要求传入产品ID数组而非对象数组,再做简单转换。

修改后的完整代码

<?php
// 假设$products已经是你筛选好的产品对象数组(WP_Post或WC_Product)
$slider_args = array(
    'slides_per_view' => 4,
    'img_size' => 'woocommerce_thumbnail',
    'custom_sizes' => false
);

theme_set_loop_prop('products_view', 'carousel');

// 替换第三个参数为你的筛选产品数组$products
echo theme_generate_posts_slider($slider_args, false, $products);

wp_reset_postdata(); // 重置全局post数据,避免影响后续内容
?>

适配说明

如果主题的theme_generate_posts_slider函数要求传入产品ID数组而非对象数组,把$products转成ID数组即可:

// 转换为产品ID数组
$product_ids = wp_list_pluck($products, 'ID');
// 传入滑块函数
echo theme_generate_posts_slider($slider_args, false, $product_ids);

额外说明

主题的theme_generate_posts_slider内部会自动遍历你传入的产品数组,调用对应的产品模板(类似你之前用的wc_get_template_part),所以不需要自己写foreach循环输出。


内容的提问来源于stack exchange,提问作者Ahodhellysar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:51:46