Skip to content

Instantly share code, notes, and snippets.

@LucaRosaldi
Last active April 28, 2022 10:12
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 LucaRosaldi/2a68d4348b435b8cc239af451eb88fd1 to your computer and use it in GitHub Desktop.
Save LucaRosaldi/2a68d4348b435b8cc239af451eb88fd1 to your computer and use it in GitHub Desktop.
WP: extend search results including tags
<?php
/**
* Extend search results query including tags.
*
* @hook posts_where, posts_join, posts_groupby
*
* @param string
* @return string
*/
function my_theme_search_where_clause_include_tags( string $where ) : string
{
if ( is_search() ) {
global $wpdb;
$where .= "OR (t.name LIKE '%".get_search_query()."%' AND {$wpdb->posts}.post_status = 'publish')";
}
return $where;
}
function my_theme_search_join_clause_include_tags( string $join ) : string
{
if ( is_search() ) {
global $wpdb;
$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 my_theme_search_groupby_clause_group_by_post_id( string $groupby ) : string
{
// we need to group on post ID
global $wpdb;
$groupby_id = "{$wpdb->posts}.ID";
// on normal query (not search), or if the clause is already present, do nothing
if( !is_search() || strpos( $groupby, $groupby_id ) !== false ) {
return $groupby;
}
// groupby was empty, use ours
if( !strlen( trim( $groupby ) ) ) {
return $groupby_id;
}
// wasn't empty, append ours
return $groupby . ", " . $groupby_id;
}
add_filter( 'posts_where','my_theme_search_where_clause_include_tags' );
add_filter( 'posts_join', 'my_theme_search_join_clause_include_tags' );
add_filter( 'posts_groupby', 'my_theme_search_groupby_clause_group_by_post_id' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment