Skip to content

Instantly share code, notes, and snippets.

@butlerblog
Created January 10, 2023 18:01
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 butlerblog/17c0d6b68ba81a161773dd0d0c87a1ee to your computer and use it in GitHub Desktop.
Save butlerblog/17c0d6b68ba81a161773dd0d0c87a1ee to your computer and use it in GitHub Desktop.
Add meta data to WordPress default search
<?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