Instantly share code, notes, and snippets.

@grola /functions.php
Last active Mar 26, 2018

Embed
What would you like to do?
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

This comment has been minimized.

Show comment
Hide comment
@grola
Owner

grola commented Jan 26, 2018

Use with gists:

  1. Category
  2. Product Category
@kanlukasz

This comment has been minimized.

Show comment
Hide comment
@kanlukasz

kanlukasz Mar 26, 2018

Hi, thanks for code.
It is possible (in Woocommerce) to search by custom fields (values)?

kanlukasz commented Mar 26, 2018

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