This is normal that it doesn’t return anything as you need to pass this $args
in a WP_Query
first and to call a the product template in a loop this way:
if( ! function_exists('product_test') ) {
// Add Shortcode
function product_test( $atts ) {
global $woocommerce_loop;
// Attributes
$atts = shortcode_atts(
array(
'columns' => '4',
'limit' => '20',
'start' => current_time('Ymd'),
'end' => current_time('Ymd'),
),
$atts, 'products_test'
);
$woocommerce_loop['columns'] = $atts['columns'];
// The WP_Query
$products = new WP_Query( array (
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => $atts['limit'],
'meta_query' => array(
'relation' => 'AND',
'start_clause' => array(
'key' =>'flash_sale_start',
'value' => $atts['today'],
'compare' => '<=',
'type' => 'DATE'
),
'end_clause' => array(
'key' => 'flash_sale_end',
'value' => $atts['today'],
'compare' => '>=',
'type' => 'DATE'
),
)
));
ob_start();
if ( $products->have_posts() ) { ?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php
} else {
do_action( "woocommerce_shortcode_products_loop_no_results", $atts );
echo "<p>There is no results.</p>";
}
woocommerce_reset_loop();
wp_reset_postdata();
return '<div class="woocommerce columns-' . $atts['columns'] . '">' . ob_get_clean() . '</div>';
}
add_shortcode( 'products_test', 'product_test' );
}
Code goes in function.php file of the active child theme (or active theme).
USAGE:
There is 4 available optional arguments that you can add to this shortcode:
columns
(The number of columns) – Default is 4limit
(the number of products | -1 will display all ) – Default is 20start
(Start date | format is ‘YMD’ ) – Default is todayend
(End date | format is ‘YMD’ ) – Default is today
You can set any more in the function… You can change default values too.
Example 1 (simple with default values):
[products_test]
Example 2 (some custom values)
[products_test columns='3' limit='15']