To show “% discount” in a facet, we’ll first create the facet:

We’re setting the Data source to Post Type just as a placeholder.

Next, we add an indexer hook to calculates the percent discount and modify the index value. Add the following into your (child) theme’s functions.php:

How to use custom PHP code?

PHP code can be added to your (child) theme's functions.php file. Alternatively, you can use the Custom Hooks add-on, or a code snippets plugin. More info

add_filter( 'facetwp_index_row', function( $params, $class ) { if ( 'percent_discount' == $params['facet_name'] ) { $post_id = (int) $params['post_id']; if ( 'product' == get_post_type( $post_id ) ) { $product = wc_get_product( $post_id ); $discount = 0; if ( $product ) { $regular_price = $product->get_regular_price(); $sale_price = $product->get_sale_price(); $discount = round( 100 * ( $regular_price - $sale_price ) / $regular_price ); } $params['facet_value'] = $discount; $params['facet_display_value'] = $discount; } } return $params; }, 10, 2 );

Make sure to re-index afterwards.

See also

Last updated: September 10, 2024