将一组产品 ID 动态传递给 Woocommerce "products" 简码

Pass dynamically an array of product IDs to Woocommerce "products" shortcode

我正在使用一个主题并有一个自定义 post 类型 'Seller'。我在 WooCommerce 中有产品,其中产品通过高级自定义字段分配给卖家。在我的单身 seller.php 中,我有:

<?php echo do_shortcode('[products]'); ?>

其中returns产品完美的作为主题的意向。我有一个查询,我可以通过它进行查询并显示我自己的代码:

$relatedProducts = get_posts(array(
    'meta_query' => array(
        array(
            'key' => 'seller', //ACF field name
            'value' => get_the_ID(),
            'compare' => 'LIKE'
        ),
    ),
    'numposts' => -1,
    'post_status' => 'publish',
    'post_type' => 'product',
));

我可以向简码传递一个 ids 参数吗?最好的方法是什么?

<?php echo do_shortcode('[products ids=""]'); ?>

大家干杯。

是你自己的简码吗?以下是如何创建带参数的简码:https://developer.wordpress.org/plugins/shortcodes/shortcodes-with-parameters/

并且在查询中你必须添加

'post__in' => array(<put list of id here, separated by comma>)

已经有 an ids argument 的 woocommerce [products] 简码可以使用...

get_posts() 函数中,您将添加参数数组:

'fields'     => 'ids',

获取一系列产品 ID…

然后使用 implode() 函数将您的产品 ID 数组转换为 ID 字符串,您将能够将 ID 作为字符串包含在您的简码中,这样:

<?php // Your query
$related_ids = get_posts(array(
    'meta_query'  => array(
        array(
            'key'     => 'seller', //ACF field name
            'value'   => get_the_ID(),
            'compare' => 'LIKE'
        ),
    ),
    'numposts'    => -1,
    'post_status' => 'publish',
    'post_type'   => 'product',
    'fields'      => 'ids', // <==== HERE to get an array of IDs
)); ?>

<?php echo do_shortcode("[products ids='".implode(',',$related_ids)."']"); ?>

已测试并有效。