Recount posts in terms
-
Hi there,
I have written a PHP snippet that conditionally add a tax_query in the wpc_filtered_query_end action. However, when the custom tax_query is activated, the counts of posts in the terms in other filters is wrong.
Is there some other place, the query should be changed, or should I call an action in order to refresh the count?
The code for reference
function expand_search($query) {
if (!is_admin() && null != $query->get('s') && '' != $query->get('s') && !empty($query->get('s'))){
$search_query_term = $query->get('s');
if (!$search_query_term) return;
// Split the search query into terms
$query_terms = explode(' ', $search_query_term);
$query_terms[] = $search_query_term; // Add the full search term to the array
$query_terms = array_map('sanitize_text_field', $query_terms); // Sanitize each term
// Initialize arrays for matching term IDs
$matching_forfattere = array();
$matching_temaer = array();
// Loop through each term and add matching forfatter and category term IDs
foreach ($query_terms as $query_term) {
$forfatter_terms = get_terms(array(
'taxonomy' => 'forfatter',
'fields' => 'ids',
'name__like' => $query_term,
'hide_empty' => false,
));
$temaer_terms = get_terms(array(
'taxonomy' => 'category',
'fields' => 'ids',
'name__like' => $query_term,
'hide_empty' => false,
));
// Merge the IDs to avoid overwriting in each iteration
$matching_forfattere = array_merge($matching_forfattere, $forfatter_terms);
$matching_temaer = array_merge($matching_temaer, $temaer_terms);
}
// Remove duplicate IDs from the arrays
$matching_forfattere = array_unique($matching_forfattere);
$matching_temaer = array_unique($matching_temaer);
if (!empty($matching_forfattere) || !empty($matching_temaer)) {
$query->set('s', '');
// Get any existing tax_query and combine it with the new one
$existing_tax_query = $query->get('tax_query') ?: array();
// Add our custom tax queries
$custom_tax_query = array(
'relation' => 'OR',
array(
'taxonomy' => 'forfatter',
'field' => 'term_id',
'terms' => $matching_forfattere,
),
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $matching_temaer,
),
);
// Merge existing tax_query with custom_tax_query
$merged_tax_query = array_merge($existing_tax_query, array($custom_tax_query));
// Set the combined tax_query
$query->set('tax_query', $merged_tax_query);
}
}
}
add_action('wpc_filtered_query_end', 'expand_search', 9999999999999);
Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
- You must be logged in to reply to this topic.