Skip to content

Instantly share code, notes, and snippets.

@EricBusch
Last active November 6, 2022 11:05
Show Gist options
  • Save EricBusch/18600dafb94b837638f7509cfe69272b to your computer and use it in GitHub Desktop.
Save EricBusch/18600dafb94b837638f7509cfe69272b to your computer and use it in GitHub Desktop.
This code adds a "discount" to catalog ordering args. It makes it possible for a user to order products on WooCommerce category pages and the main shop page by the product's discount amount. It also adds a "'Sort by discount" to sorting menus on shop page and category pages. Finally it displays the percentage you save on a discounted item. This …
<?php
/**
* Add "discount" to catalog ordering args.
*
* This makes it possible for a user to order products on category pages and the main shop
* page by the product's discount amount.
*
* @see wc_clean()
* @link http://docs.woothemes.com/document/custom-sorting-options-ascdesc/
*
* @param array $args Ordering arguments.
*
* @return array Updated $args array.
*/
add_filter( 'woocommerce_get_catalog_ordering_args', 'mycode_add_salediscount_to_woocommerce_catalog_ordering_args' );
function mycode_add_salediscount_to_woocommerce_catalog_ordering_args( $args ) {
$orderby_value = isset( $_GET['orderby'] ) ?
wc_clean( $_GET['orderby'] ) :
apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
if ( 'discount' == $orderby_value ) {
$args['orderby'] = 'meta_value_num';
$args['order'] = 'DESC';
$args['meta_key'] = '_dfrps_salediscount';
}
return $args;
}
/**
* Adds "'Sort by discount" to sorting menus on shop page and category pages.
*
* @link https://docs.woocommerce.com/document/custom-sorting-options-ascdesc/
*
* @param array $sortby Array of keys to sort by.
*
* @return array Updated $sortby array.
*/
add_filter( 'woocommerce_default_catalog_orderby_options', 'mycode_woocommerce_add_salediscount_to_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'mycode_woocommerce_add_salediscount_to_catalog_orderby' );
function mycode_woocommerce_add_salediscount_to_catalog_orderby( $sortby ) {
$sortby['discount'] = 'Sort by discount';
return $sortby;
}
/**
* Displays the percentage you save on a discounted item.
*
* This will echo HTML like "Save 34%" near the price of a product which is on sale.
*
* @global WC_Product $product
*/
add_action( 'woocommerce_after_shop_loop_item', 'mycode_show_discount_in_product_lists' ); // Product Loop
add_action( 'woocommerce_single_product_summary', 'mycode_show_discount_in_product_lists' ); // Product Page
function mycode_show_discount_in_product_lists() {
global $product;
$salediscount = get_post_meta( $product->id, '_dfrps_salediscount', true );
if ( $salediscount > 0 ) {
echo '<div class="dfrps_salediscount">';
echo 'Save ' . $salediscount . '%';
echo '</div>';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment