Created
July 8, 2015 18:22
-
-
Save jprieton/b358f37b0f9e8777f901 to your computer and use it in GitHub Desktop.
WordPress Search in taxonomy
This file contains 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_filter('posts_search', function ($search, &$wp_query) { | |
global $wpdb; | |
if (empty($search) || is_admin()) { | |
return $search; // skip processing - no search term in query | |
} | |
$s = get_query_var('s'); | |
// SEARCH IN TAXONOMY | |
$term_query = "OR (" | |
. "{$wpdb->posts}.ID IN (" | |
. "SELECT object_id as ID " | |
. "FROM {$wpdb->terms} " | |
. "JOIN {$wpdb->term_relationships} ON {$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->terms}.term_id " | |
. "JOIN {$wpdb->term_taxonomy} USING (term_id) " // In specific taxonomy | |
. "WHERE {$wpdb->terms}.name LIKE '%{$s}%' " | |
. "AND {$wpdb->term_taxonomy}.taxonomy = 'post_tag')" // In specific taxonomy | |
. ")"; | |
$search .= " AND ({$wpdb->posts}.post_title <> '') "; // exclude empty titles | |
$search .= " AND ({$wpdb->posts}.post_status = 'publish') "; | |
return $search . $term_query; | |
}, 500, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment