Skip to content

Instantly share code, notes, and snippets.

@searchwpgists
Created March 27, 2026 18:58
Show Gist options
  • Select an option

  • Save searchwpgists/cdba67890c5595c199af0b27f7f1b0bb to your computer and use it in GitHub Desktop.

Select an option

Save searchwpgists/cdba67890c5595c199af0b27f7f1b0bb to your computer and use it in GitHub Desktop.
Order product search results by total sales
<?php
// Order product search results by total sales
add_filter( 'searchwp\query\mods', function( $mods, $query ) {
global $wpdb;
$mod = new \SearchWP\Mod();
$alias = \SearchWP::$index->get_alias();
$meta_alias = 'my_searchwp_sort_products';
$meta_key = 'total_sales';
$mod->column_as( $wpdb->prepare( "(
SELECT meta_value
FROM {$wpdb->postmeta}
WHERE
{$wpdb->postmeta}.post_id = {$alias}.id
AND {$wpdb->postmeta}.meta_key = %s
)", $meta_key ),
$meta_alias );
$mod->order_by( "{$meta_alias} + 0", 'DESC', 5 );
$mods[] = $mod;
return $mods;
}, 30, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment