Created
January 10, 2023 18:01
-
-
Save butlerblog/17c0d6b68ba81a161773dd0d0c87a1ee to your computer and use it in GitHub Desktop.
Add meta data to WordPress default search
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 | |
add_action( 'pre_get_posts', array( $this, 'search_metadata' ), 9 ); | |
function search_metadata() { | |
if ( ! is_main_query() || ! is_search() ) { | |
return; | |
} | |
add_filter( 'posts_join', function( $join ) { | |
global $wpdb; | |
return $join .' LEFT JOIN ' . $wpdb->postmeta . ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id '; | |
} ); | |
add_filter( 'posts_where', function ( $where ) { | |
global $wpdb; | |
$or = array( | |
"(".$wpdb->posts.".post_title LIKE $1)", | |
"(".$wpdb->postmeta.".meta_value LIKE $1)", | |
); | |
if ( is_main_query() && is_search() ) { | |
$where = preg_replace( | |
"/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/", | |
implode( ' OR ', $or ), | |
$where | |
); | |
} | |
return $where; | |
} ); | |
add_filter( 'posts_distinct', function () { | |
global $wpdb; | |
return "DISTINCT"; | |
} ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment