-
-
Save searchwpgists/85b00e6b97d8ceb315fcb4e7f1cde8c3 to your computer and use it in GitHub Desktop.
Boost relevance for WooCommerce products with high total sales
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // Boost relevance for WooCommerce products with high total sales | |
| add_filter( 'searchwp\query\mods', function( $mods, $query ) { | |
| global $wpdb; | |
| // Adjustable variables | |
| $min_total_sales = 100; // Minimum sales required to qualify | |
| $bonus_weight = 99999; // Base relevance weight | |
| $sales_multiplier = 100; // Extra relevance per sale | |
| $search_term = trim( $query->get_keywords() ); | |
| if ( empty( $search_term ) ) { | |
| return $mods; | |
| } | |
| $mod = new \SearchWP\Mod(); | |
| $mod->set_local_table( $wpdb->posts ); | |
| $mod->on( 'ID', [ 'column' => 'id' ] ); | |
| $mod->relevance( function( $runtime ) use ( $wpdb, $min_total_sales, $bonus_weight, $sales_multiplier ) { | |
| $alias = $runtime->get_local_table_alias(); | |
| return " | |
| CASE | |
| WHEN {$alias}.post_type = 'product' | |
| AND ( | |
| SELECT CAST(pm.meta_value AS UNSIGNED) | |
| FROM {$wpdb->postmeta} pm | |
| WHERE pm.post_id = {$alias}.ID | |
| AND pm.meta_key = '_total_sales' | |
| LIMIT 1 | |
| ) >= {$min_total_sales} | |
| THEN | |
| {$bonus_weight} + | |
| ( | |
| SELECT CAST(pm.meta_value AS UNSIGNED) | |
| FROM {$wpdb->postmeta} pm | |
| WHERE pm.post_id = {$alias}.ID | |
| AND pm.meta_key = '_total_sales' | |
| LIMIT 1 | |
| ) * {$sales_multiplier} | |
| ELSE 0 | |
| END | |
| "; | |
| }); | |
| $mods[] = $mod; | |
| return $mods; | |
| }, 20, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment