Last active
June 6, 2021 16:16
[WP] Include terms in WordPress standard search results + WPML compatibility
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 | |
function custom_search_where($where){ | |
global $wpdb; | |
if (is_search() && get_search_query()) | |
$where .= "OR ((t.name LIKE '%".get_search_query()."%' OR t.slug LIKE '%".get_search_query()."%') AND {$wpdb->posts}.post_status = 'publish')"; | |
// WPML | |
if (function_exists('icl_get_languages')) { | |
$lang_code = 'it'; // better set a default lang code as fallback here | |
if(defined('ICL_LANGUAGE_CODE') && ICL_LANGUAGE_CODE != '') { | |
$lang_code = ICL_LANGUAGE_CODE; | |
} | |
$where .= "AND language_code = '".$lang_code."'"; | |
} | |
return $where; | |
} | |
function custom_search_join($join){ | |
global $wpdb; | |
if (is_search()&& get_search_query()) | |
$join .= "LEFT JOIN {$wpdb->term_relationships} tr ON {$wpdb->posts}.ID = tr.object_id INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id=tr.term_taxonomy_id INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id"; | |
return $join; | |
} | |
function custom_search_groupby($groupby){ | |
//if(is_admin()) return; | |
global $wpdb; | |
// we need to group on post ID | |
$groupby_id = "{$wpdb->posts}.ID"; | |
if(!is_search() || strpos($groupby, $groupby_id) !== false || !get_search_query()) return $groupby; | |
// groupby was empty, use ours | |
if(!strlen(trim($groupby))) return $groupby_id; | |
// wasn't empty, append ours | |
return $groupby.", ".$groupby_id; | |
} | |
if(!is_admin()) { | |
add_filter('posts_where','custom_search_where'); | |
add_filter('posts_join', 'custom_search_join'); | |
add_filter('posts_groupby', 'custom_search_groupby'); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment