Site logo

Archived topic

Search results grouped by the different custom post types

9 replies · Started by Jaume on March 23, 2023

Viewing posts 1–10 of 10

Hi. I've created 3 custom post types, so now I have 4 post types in my site: posts, opinions, dictionary and companies. When I search a word, the results appear all mixed up, sorted by date, but I'd like to have them sorted by each post type.

I'm using the INFO template from the site library and it comes with the search results block, but I can't figure out how to achieve what I need. Do I have to modify the search results block to have a loop for each custom post type? In this case, how (because I cannot find where I can change this loop)?

How do I have to do this? Thank you very much.

Raquel

Hi Raquel,

I’m using the INFO template from the site library and it comes with the search results block

I built the Info template, but I don't recall there being a block called search result block.

Can you explain a bit more or point me to the search result block you are referring to?

Achieving what you are looking for will require custom PHP coding.

Can you try this?

function search_filter($query) {
    if ($query->is_search && !is_admin()) {
        $query->set('post_type', array( 'post','opinion','dictionary','company'));
	$query->set('orderby', 'type');
        $query->set('order', 'ASC');
		
    }
    return $query;
}

add_filter('pre_get_posts','search_filter');

Adding PHP: https://docs.generatepress.com/article/adding-php/

Hi Ying. This is not exactly what I need to do. Let me try to explain. When I serach for a word, I need the results to show like this:

POST
--------
All results from post.

OPINION
------------
All results from opinion.

DICTIONARY
-------------
All results from dictionary.

COMPANY
------------
All results from company.

I understand I need to create a custom results block, but I don't know how. Any idea? Thanks.

I understand I need to create a custom results block, but I don’t know how

There's no way to use block to achieve what you are looking for unfortunately.

Not even using custom PHP?

No, sorry, this is not what I want to do: this code just shows me results from this 4 post types, ordered by date (as it is supposed to be shown, in the other hand). But my client wants the results page ordered by post type like this:

POST
——–
All results from post.

OPINION
————
All results from opinion.

DICTIONARY
————-
All results from dictionary.

COMPANY
————
All results from company.

Is there a way, using functions? Or should I repurpose the search.php page?

Can you provide the link to the site in question?

Keep the code by Ying added. We'll check what's occurring.

Let me ask my client if I can send you the password, because now is behind a protection.

This archived topic is closed to new replies.