WooCommerce product shortcode showing only in stock products

WooCommerce product shortcode – stock products only

In WooCommerce, to display only in-stock products using a shortcode, you can use the [products] shortcode with additional parameters to filter the products. Unfortunately, the default WooCommerce shortcodes do not provide a direct way to filter by stock status. However, you can achieve this with a custom shortcode.

Here’s how you can create a custom shortcode to display only in-stock products:

  1. Add the Custom Shortcode to Your Theme’s functions.php File:Add the following code to your theme’s functions.php file. This code creates a new shortcode [in_stock_products] that queries and displays only in-stock products.
    
    function in_stock_products_shortcode($atts) {
        ob_start();
    
        // Define default attributes
        $atts = shortcode_atts(array(
            'limit' => '10',    // Default limit to 10 products
            'columns' => '4',   // Default to 4 columns
        ), $atts, 'in_stock_products');
    
        // WP_Query arguments
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => $atts['limit'],
            'post_status' => 'publish',
            'meta_query' => array(
                array(
                    'key' => '_stock_status',
                    'value' => 'instock',
                ),
            ),
        );
    
        // Query products
        $loop = new WP_Query($args);
    
        // Check if there are products
        if ($loop->have_posts()) {
            echo '
      '; while ($loop->have_posts()) : $loop->the_post(); wc_get_template_part('content', 'product'); endwhile; echo '
    '; } else { echo __('No products found'); } // Reset Post Data wp_reset_postdata(); return ob_get_clean(); } // Register the shortcode add_shortcode('in_stock_products', 'in_stock_products_shortcode');
  2. Use the Custom Shortcode in Your Posts or Pages

    Now you can use the custom shortcode [in_stock_products] in your posts or pages. You can also specify the number of products to display and the number of columns:

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

    This example will display 12 in-stock products in 3 columns. Adjust the limit and columns attributes as needed for your specific requirements.

    Summary

    • Add the provided PHP code to your theme’s functions.php file.
    • Use the [in_stock_products] shortcode in your content to display only in-stock products.
    • Customize the limit and columns attributes to fit your layout needs.
5/5 - (1 vote)

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top