Skip to content

Instantly share code, notes, and snippets.

@grola
Last active March 26, 2018 08:18
Show Gist options
  • Save grola/0fb307ca2e0806133fa287ff199cfd47 to your computer and use it in GitHub Desktop.
Save grola/0fb307ca2e0806133fa287ff199cfd47 to your computer and use it in GitHub Desktop.
Search by product category and product tag
<?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;
}
}
@grola
Copy link
Author

grola commented Jan 26, 2018

Use with gists:

  1. Category
  2. Product Category

@kanlukasz
Copy link

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