Load Woocommerce Loop With Custom Arguments

Woocommerce comes with many default shortcode that generally used in e-commerce website. Some of my project required different arguments to be passed on to woocommerce product query. I need to change the woocommerce shortcode behaviour to meet my project needs.

I want to display sale products but with offset options. So I create another custom shortcode to add the offset attribute and using the woocommerce loop to display my results.

Here is the snippet. You just need to copy and paste it to your theme’s functions.php file.

function oto_sale_products_func( $atts ) {
	$atts = shortcode_atts( array(
		'per_page' => '12',
		'columns'  => '4',
		'orderby'  => 'date',
		'order'    => 'desc',
		'offset'   => 0,
		'category' => '', // Slugs
		'operator' => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
	), $atts, 'sale_products' );

	ob_start();

	$query_args = array(
		'posts_per_page' => $atts['per_page'],
		'orderby'        => $atts['orderby'],
		'order'          => $atts['order'],
		'offset'         => $atts['offset'],
		'no_found_rows'  => 1,
		'post_status'    => 'publish',
		'post_type'      => 'product',
		'meta_query'     => WC()->query->get_meta_query(),
		'post__in'       => array_merge( array( 0 ), wc_get_product_ids_on_sale() )
	);
	?>
	<ul class="products">
		<?php
			$loop = new WP_Query( $query_args );
			if ( $loop->have_posts() ) {
				while ( $loop->have_posts() ) : $loop->the_post();
					wc_get_template_part( 'content', 'product' );
				endwhile;
			} else {
				echo __( 'No products found' );
			}
			wp_reset_postdata();
		?>
	</ul><!--/.products-->
	<?php

	return '<div class="woocommerce columns-' . $columns . '">' . ob_get_clean() . '</div>';

}

add_shortcode( 'oto_sale_products', 'oto_sale_products_func' );

Leave A Comment