Skip to content

Instantly share code, notes, and snippets.

@brisbanewebdeveloper
Created March 21, 2019 14:04
Show Gist options
  • Save brisbanewebdeveloper/50109f98ac99b752c0cee15c7008eac1 to your computer and use it in GitHub Desktop.
Save brisbanewebdeveloper/50109f98ac99b752c0cee15c7008eac1 to your computer and use it in GitHub Desktop.
Include Attributes for WordPress/WooCommerce Search
/**
* Include Attributes for search
* @return array|null
*/
function getProductSearchClauses() {
/* @var WP_Query $wp_query */
global $wp_query;
global $wpdb;
static $clauses = null;
if (is_null($clauses)) {
$s = get_query_var('s');
$tax_query = array();
$attributes = array(
'my_attribute_1',
'my_attribute_2',
'my_attribute_3',
);
foreach ($attributes as $a) {
$termIds = get_terms(array(
'taxonomy' => $a,
'fields' => 'tt_ids',
'name__like' => $s,
));
$tax_query[] = array(
'taxonomy' => $a,
'terms' => $termIds,
);
}
$tax_query = array(
'tax_query' => $tax_query,
'cat' => null,
'tag' => null,
);
$wp_query->parse_tax_query($tax_query);
/* @var WP_Tax_Query $wp_tax_query */
$wp_tax_query = $wp_query->tax_query;
$relation = null;
if ( ! empty($wp_tax_query->queries['relation'])) { // Remember the current state to revert later
$relation = $wp_tax_query->queries['relation'];
}
$wp_tax_query->queries['relation'] = 'OR';
$clauses = $wp_tax_query->get_sql($wpdb->posts, 'ID');
if ( ! empty($relation)) $wp_tax_query->queries['relation'] = $relation; // Revert
$clauses['where'] = preg_replace('/^ AND /', '', $clauses['where']);
}
return $clauses;
}
/**
* @param string $where
* @param WP_Query $query
* @return string|string[]|null
*/
function my_posts_where($where, $query) {
if ($query->is_search() && $query->is_main_query()) {
$clauses = getProductSearchClauses();
return preg_replace('/(\(wp_posts.post_title LIKE)/', $clauses['where'] . ' OR $1', $where);
} else {
return $where;
}
}
add_filter('posts_where', 'my_posts_where', 10, 2);
/**
* @param string $join
* @param WP_Query $query
* @return string
*/
function my_posts_join($join, $query) {
if ($query->is_search() && $query->is_main_query()) {
$clauses = getProductSearchClauses();
$join .= $clauses['join'];
}
return $join;
}
add_filter('posts_join', 'my_posts_join', 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment