Created
May 3, 2021 09:11
-
-
Save obiPlabon/6c6e6edc8e5114ae0ba97e63d9ef52ec to your computer and use it in GitHub Desktop.
WP Search by ID and fallback to regular search query
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 | |
/** | |
* Search by post ID when integer is available in search terms. | |
* Fallback to regular query when integer is absent. | |
* | |
* @param string $search Search sql query string | |
* @param WP_Query $query | |
* | |
* @return string | |
*/ | |
function wp_search_by_id_only( $search, $query ) { | |
global $wpdb; | |
if ( empty( $search ) ) { | |
return $search; // skip processing - no search term in query | |
} | |
$q = $query->query_vars; | |
$ids = []; | |
foreach ( (array) $q['search_terms'] as $term ) { | |
$term = absint( $term ); | |
if ( $term > 0 ) { | |
$ids[] = $term; | |
} | |
} | |
if ( count( $ids ) > 0 ) { | |
$ids_holder = ltrim( str_repeat( ',%d', count( $ids ) ), ',' ); | |
$search = $wpdb->prepare( "AND ({$wpdb->posts}.ID IN({$ids_holder}))", $ids ); | |
} | |
return $search; | |
} | |
add_filter( 'posts_search', 'wp_search_by_id_only', 500, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment