Last active
October 20, 2022 10:40
-
-
Save opicron/571292e342a19a7c7151b0ecd7521747 to your computer and use it in GitHub Desktop.
filter search results #php #searchwp
This file contains hidden or 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 | |
function filter_the_posts($posts, &$wp_query) { | |
if( is_search() ) | |
{ | |
//make array of product ids | |
$ids = array(); | |
foreach ($posts as $key => $post) | |
{ | |
$ids[$post->ID] = $post->ID; | |
} | |
//var_dump($posts); | |
//echo '<br><br>'; | |
$filtered_posts = array(); | |
foreach ($posts as $key => $post) | |
{ | |
//check if product has parent id | |
$group_args = array( | |
'post_type' => 'product', | |
'meta_query' => array( | |
array( | |
'key' => '_children', | |
'value' => 'i:' . $post->ID . ';', | |
'compare' => 'LIKE', | |
) | |
), | |
'fields' => 'ids' // THIS LINE FILTERS THE SELECT SQL | |
); | |
$parents = get_posts( $group_args ); | |
$parentid = count($parents) > 0 ? array_shift($parents) : false; | |
if (!$parentid) | |
{ | |
$filtered_posts[] = $post; | |
} | |
else | |
{ | |
//echo 'parentid:'. $parentid; | |
if ( is_array($ids) ) | |
{ | |
if ( !in_array($parentid, $ids) ) | |
{ | |
//get parent id | |
//echo 'not found in array'; | |
$filtered_posts[] = get_post($parentid); | |
//unset($wp_query[$key]); | |
$ids[] = $parentid; | |
//var_dump($filtered_posts); | |
} | |
} | |
//var_dump($post->ID); | |
//$wp_query->request = str_replace($post->ID.',', '', $wp_query->request); | |
} | |
} | |
/* hacky slashy */ | |
global $woocommerce_loop; | |
$woocommerce_loop['paged'] = (isset($woocommerce_loop['paged'])) ? $woocommerce_loop['paged'] : 1; | |
$woocommerce_loop['total'] = count($filtered_posts); | |
$woocommerce_loop['post_count'] = count($filtered_posts); | |
$woocommerce_loop['per_page'] = 12; | |
$woocommerce_loop['total_pages'] = ceil(count($filtered_posts)/12); | |
//$woocommerce_loop['current_page'] = $args['paged']; | |
//var_dump($wp_query->request);; | |
$wp_query->posts = $filtered_posts; | |
//unset($wp_query->posts); | |
//unset($GLOBALS['wp_query']); | |
//$GLOBALS['wp_query'] =& $GLOBALS['wp_the_query']; | |
//wp_reset_postdata(); // <-- RESET QUERY | |
return $filtered_posts; | |
//return $posts; | |
} | |
return $posts; | |
} | |
//add_filter('the_posts','filter_the_posts',10,1); | |
add_filter( 'posts_results', 'filter_the_posts',10, 2 ); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment