Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kloon
Last active June 17, 2023 22:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kloon/4604038 to your computer and use it in GitHub Desktop.
Save kloon/4604038 to your computer and use it in GitHub Desktop.
WooCommerce Sale Products shortcode
<?php
add_shortcode( 'sale_products', 'sale_products' );
function sale_products( $atts ){
global $woocommerce_loop, $woocommerce;
extract( shortcode_atts( array(
'per_page' => '12',
'columns' => '4',
'orderby' => 'title',
'order' => 'asc'
), $atts ) );
// Get products on sale
$product_ids_on_sale = woocommerce_get_product_ids_on_sale();
$meta_query = array();
$meta_query[] = $woocommerce->query->visibility_meta_query();
$meta_query[] = $woocommerce->query->stock_status_meta_query();
$args = array(
'posts_per_page'=> $per_page,
'orderby' => $orderby,
'order' => $order,
'no_found_rows' => 1,
'post_status' => 'publish',
'post_type' => 'product',
'orderby' => 'date',
'order' => 'ASC',
'meta_query' => $meta_query,
'post__in' => $product_ids_on_sale
);
ob_start();
$products = new WP_Query( $args );
$woocommerce_loop['columns'] = $columns;
if ( $products->have_posts() ) : ?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php woocommerce_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php endif;
wp_reset_postdata();
return ob_get_clean();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment