First of all, the product search in the WP admin does not use Relevanssi reliably, even if you enable admin searches in Relevanssi. It just may not work, for reasons I don’t fully understand and have not been able to replicate.
Anyway, the in-stock weight boost snippet works. Here’s how you should use it, in order to avoid heavy database load:
function rlv_has_term( $term, $taxonomy, $post_id ) {
global $wpdb, $relevanssi_taxonomy_cache;
if ( isset( $relevanssi_taxonomy_cache[ $taxonomy ] ) ) {
return isset( $relevanssi_taxonomy_cache[ $taxonomy ][ $term ][ $post_id ] );
}
$taxonomy_array = $wpdb->get_results(
"SELECT t.slug, object_id FROM $wpdb->term_relationships AS tr,
$wpdb->term_taxonomy AS tt, $wpdb->terms AS t
WHERE tr.term_taxonomy_id = tt.term_taxonomy_id
AND tt.taxonomy = '$taxonomy' AND t.term_id = tt.term_id" );
foreach ( $taxonomy_array as $term_object ) {
$relevanssi_taxonomy_cache[ $taxonomy ][ $term_object->slug ][ $term_object->object_id ] = true;
}
return isset( $relevanssi_taxonomy_cache[ $taxonomy ][ $term ][ $post_id ] );
}
add_filter( 'relevanssi_match', 'rlv_woo_stocklevel' );
function rlv_woo_stocklevel( $match ) {
$in_stock = true;
if ( rlv_has_term( 'outofstock', 'product_visibility', $match->doc ) ) {
// Product is not in stock.
$in_stock = false;
}
if ( $in_stock ) {
// If product is in stock, multiply the weight by 10.
$match->weight *= 10;
}
return $match;
}
If this doesn’t have any effect, then the search is not Relevanssi. The effect may not be big enough, in which case you can multiply the weight by 100 instead of multiplying by 10. That should create a more visible effect.
You can also test this by using the Relevanssi admin search (Dashboard > Admin search). That’s guaranteed to use Relevanssi and it will also show you the weights, so you can see whether this has any effect or not.
Another option is to not use weights, but instead just sort by taxonomy:
add_filter( 'relevanssi_hits_filter', 'in_stock_first' );
function in_stock_first( $hits ) {
$in_stock = array();
$everything_else = array();
foreach ( $hits[0] as $_post ) {
$post_object = relevanssi_get_an_object( $_post )['object'];
$is_in_stock = true;
if ( rlv_has_term( 'outofstock', 'product_visibility', $post_object->ID ) ) {
$is_in_stock = false;
}
$is_in_stock ? array_push( $in_stock, $_post ) : array_push( $everything_else, $_post );
}
$hits[0] = array_merge( $in_stock, $everything_else );
return $hits;
}
This also uses the rlv_has_term() function for increased performance, so make sure that is available. This function doesn’t care about weights, it just keeps the posts in the same relevance order, but puts all in-stock products first.
-
This reply was modified 2 years, 6 months ago by Mikko Saari.