0
votes

I am trying to create a simple custom Woocommerce products shortcode which will get a list of products like this:

[custom_products_list ids='32,21,44,56']

And will output products with URL, Title, Ordeing by Name and ACS No other info needed, no thumbnail or other. Just the above. I do not want to use the default products shortcode on purpose.

I would appreciate any help! Thanks in advance!

1

1 Answers

0
votes

Something like this...

function custom_product_list_shortcode( $atts, $content = null ) {

    $_atts =  shortcode_atts( [
        'ids' => '',
    ], $atts );

    $ids_arr = array_filter( array_map( function( $id ){
        return trim( $id );
    }, explode( ',', $_atts['ids'] ) ) );

    $products = wc_get_products( [
        'post_status' => 'publish',
        // can't remember if it's 'orderby' or 'order_by'
        'order_by' => [
            'title' => 'ASC',
            'post_date' => 'DESC',
        ],
        'posts_per_page' => -1,
        // you can probably just pass in the comma sep string instead of array but maybe not.
        // you need to check that post__in is correct. look at the docs for WP_Query, or WC_Query, or wc_get_products()
        'post__in' => $ids_arr,
    ]);

    // you could write your own sorting function like this if you want but you probably shouldn't need to
    // rsort( $products, function( $p1, $p2 ) {});

    // the html is for you to complete
    ob_start();
    ?>
    <div class="products-list">
        <?php foreach ( $products as $product ) { ?>
            <div class="product">
                <pre>
                    <?= print_r( $product, true ); ?>
                    <?= get_title( $product->ID ); ?>
                </pre>
            </div>
        <?php } ?>
    </div>
    <?php
    return ob_get_clean();
}

add_shortcode( 'custom_product_list', 'custom_product_list_shortcode' );