Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Last active October 7, 2019 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jchristopher/7d09bb174ca29125742ca7aaab19f9d7 to your computer and use it in GitHub Desktop.
Save jchristopher/7d09bb174ca29125742ca7aaab19f9d7 to your computer and use it in GitHub Desktop.
<?php
// BETA implementation of bubbling exact matches to the top when partial matching is enabled in SearchWP
add_filter( 'searchwp_weight_mods', function( $sql ) {
global $wpdb;
$partial_matches_enabled = searchwp_get_setting_advanced( 'partial_matches' );
if ( empty( $partial_matches_enabled ) ) {
return $sql;
}
$prefix = $wpdb->prefix . SEARCHWP_DBPREFIX;
$original_terms = SWP()->sanitize_terms( SWP()->original_query );
// Retrieve exact match term IDs.
$exact_match_term_ids = $wpdb->get_col( $wpdb->prepare( "
SELECT id
FROM {$prefix}terms
WHERE term IN ( " .
implode( ', ',
array_fill( 0, count( $original_terms ), '%s' )
) .
" )
",
$original_terms ) );
if ( empty( $exact_match_term_ids ) ) {
return $sql;
}
$exact_match_post_ids = $wpdb->get_col(
$wpdb->prepare( "
SELECT {$prefix}index.post_id
FROM {$prefix}index
LEFT JOIN {$prefix}cf
ON {$prefix}index.post_id = {$prefix}cf.post_id
LEFT JOIN {$prefix}tax
ON {$prefix}index.post_id = {$prefix}tax.post_id
WHERE {$prefix}index.term IN ( "
. implode( ', ',
array_fill( 0, count( $exact_match_term_ids ), '%d' )
) .
" )
GROUP BY {$prefix}index.post_id
",
$exact_match_term_ids
)
);
if ( empty( $exact_match_post_ids ) ) {
return $sql;
}
$sql .= $wpdb->prepare( "
+ ( IF( {$wpdb->posts}.ID IN ( " .
implode( ', ',
array_fill( 0, count( $exact_match_post_ids ), '%d' )
) .
" ), 987654321, 0 ) ) ",
$exact_match_post_ids
);
return $sql;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment