I am using a plugin (Relevanssi) and a custom function to sort the search results by custom post types (see below). This is working great.
add_filter('relevanssi_hits_filter', 'separate_result_types');
function separate_result_types($hits) {
$types = array();
// Split the post types in array $types
if (!empty($hits)) {
foreach ($hits[0] as $hit) {
if (!is_array($types[$hit->post_type])) $types[$hit->post_type] = array();
array_push($types[$hit->post_type], $hit);
}
}
// Merge back to $hits in the desired order
$hits[0] = array_merge((array)$types['cats'], (array)$types['dogs'], (array)$types['horses']);
return $hits;
}
The problem arises when I want to display search results on a per-type basis. For example, when on the "Search Pets" page (which is a page template, search-pets.php) I want to display only search results for the above CPTs. When on the "Blog" page (standard WP posts), I want to display only blog posts, and if on a non custom CPT page, display page results. I thought that by adding an if/else statement (see below) that would work.
add_filter('relevanssi_hits_filter', 'separate_result_types');
function separate_result_types($hits) {
$types = array();
// Split the post types in array $types
if (!empty($hits)) {
foreach ($hits[0] as $hit) {
if (!is_array($types[$hit->post_type])) $types[$hit->post_type] = array();
array_push($types[$hit->post_type], $hit);
}
}
// If post type = dogs, cats, horses
if (in_array( get_post_type(), array('dogs','cats','horses'))){
// Merge back to $hits in the desired order
$hits[0] = array_merge((array)$types['dogs'], (array)$types['cats'], (array)$types['horses']);
// return $hits;
} else {
// If post type = posts, page
if (in_array( get_post_type(), array('post','page'))){
// Merge back to $hits in the desired order
$hits[0] = array_merge((array)$types['post'], (array)$types['page']);
//return $hits;
}}
return $hits;
}
But it only seems to return the top filter results. Any idea where I'm going wrong, or if my logic will even work? Very much a PHP noob. Thanks!
Ramsey