Last active
March 26, 2018 08:18
-
-
Save grola/0fb307ca2e0806133fa287ff199cfd47 to your computer and use it in GitHub Desktop.
Search by product category and product tag
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 | |
class studiowp_search_by_taxonomy { | |
protected $taxonomy = 'category'; | |
protected $slug = 'category'; | |
public function __construct( $taxonomy ) { | |
$this->taxonomy = $taxonomy; | |
$this->slug = str_replace( '-', '_', $this->taxonomy ); | |
add_filter( 'posts_join', array( $this, 'posts_join' ) , 10, 2 ); | |
add_filter( 'posts_where', array( $this, 'posts_where' ), 10, 2 ); | |
add_filter( 'posts_groupby', array( $this, 'posts_groupby' ), 10, 2 ); | |
} | |
public function posts_join( $join, $query ) { | |
global $wpdb; | |
if ( is_main_query() && is_search() ) { | |
$join .= " | |
LEFT JOIN | |
( | |
{$wpdb->term_relationships} AS term_relationship_search_by_taxonomy_{$this->slug} | |
INNER JOIN | |
{$wpdb->term_taxonomy} AS term_taxonomy_search_by_taxonomy_{$this->slug} | |
ON term_taxonomy_search_by_taxonomy_{$this->slug}.term_taxonomy_id = term_relationship_search_by_taxonomy_{$this->slug}.term_taxonomy_id | |
INNER JOIN | |
{$wpdb->terms} terms_search_by_taxonomy_{$this->slug} | |
ON terms_search_by_taxonomy_{$this->slug}.term_id = term_taxonomy_search_by_taxonomy_{$this->slug}.term_id | |
) | |
ON {$wpdb->posts}.ID = term_relationship_search_by_taxonomy_{$this->slug}.object_id | |
"; | |
} | |
return $join; | |
} | |
public function posts_where( $where, $query ) { | |
global $wpdb; | |
if ( is_main_query() && is_search() ) { | |
$where .= " OR ( | |
term_taxonomy_search_by_taxonomy_{$this->slug}.taxonomy = '{$this->taxonomy}' | |
AND ( | |
terms_search_by_taxonomy_{$this->slug}.name LIKE '%" . $wpdb->esc_like( get_query_var( 's' ) ) . "%' | |
) | |
)"; | |
} | |
return $where; | |
} | |
public function posts_groupby( $groupby, $query ) { | |
global $wpdb; | |
if ( is_main_query() && is_search() ) { | |
$groupby = "{$wpdb->posts}.ID"; | |
} | |
return $groupby; | |
} | |
} |
Hi, thanks for code.
It is possible (in Woocommerce) to search by custom fields (values)?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use with gists: