Search code examples
phpwordpresswoocommerceadvanced-custom-fieldsshortcode

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


I am using a theme and have a custom post type 'Seller'. I have products in WooCommerce where a product is assigned a seller through Advanced Custom fields. Within my single-seller.php I have:

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

Which returns the products perfectly as the theme is intended. I have a query which I could foreach through and display my own code:

$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',
));

Could I pass the shortcode an ids argument and what would be the best way to do this?

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

Cheers all.


Solution

  • There is already an ids argument for woocommerce [products] shortcode that you can use…

    In the get_posts() funtion you will add the the arguments array:

    'fields'     => 'ids',
    

    to get an array of products IDs…

    Then using implode() function to convert your products ids array to a string of ids, you will be able to include the ids as a string in your shortcode, this way:

    <?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)."']"); ?>
    

    Tested and works.