• Resolved Tim Burkart

    (@bigmoxy)


    Hello!

    I created the filter below to display 3 products via a custom short code on my home page. It works however I would like to know if it is possible to extend the filter’s functionality so that it will randomly return 3 products instead of always returning the same ones.

    Thank you.

    add_shortcode( 'in_stock_products', 'rompre_in_stock_products_shortcode' );
    function rompre_in_stock_products_shortcode() {
     
       $args = array(
          'post_type' => 'product',
          'posts_per_page' => 3,
          'post_status' => 'publish',
          'meta_query' => array(
             array(
                'key' => '_stock_status',
                'value' => 'instock',
             )
          ),
          'fields' => 'ids',
       );
        
       $product_ids = get_posts( $args ); 
       $product_ids = implode( ",", $product_ids );
        
       return do_shortcode("[products ids='$product_ids']");
     
    }

    The page I need help with: [log in to see the link]

Viewing 4 replies - 1 through 4 (of 4 total)
  • Try:
    'orderby' => 'rand',
    as one of the $args

    If your page is cached it may not work until the cache is refreshed.

    Thread Starter Tim Burkart

    (@bigmoxy)

    Hi @lorro,

    Not sure if it works yet but thank you! I will wait for cache to refresh.

    Thread Starter Tim Burkart

    (@bigmoxy)

    Is there a way to add parameters to a custom shortcode? For example, if my shortcode were to return all products instead of just 3, I would like to have a shortcode that resembles this:

    [in_stock_products limit="3" columns="3"]

    Temporarily deactivate your cache plugin for testing ‘rand’.

    See:
    https://codex.wordpress.org/Shortcode_API

    function rompre_in_stock_products_shortcode( $atts ) {
      $a = shortcode_atts( array(
        'limit' => 4,
        'columns' => 4,
      ), $atts );

    If parameter limit is missing, $a[‘limit’] will be 4 (default).
    If parameter limit = “3”, then $a[‘limit’] will be 3

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How to randomize selected products?’ is closed to new replies.