Jump to content

Displaying search result with link to parent


Juergen
 Share

Recommended Posts

Hello @ all,

I have a parent page (pricelist) with a lot of child pages (pricelistitems). I use the standard search code from this forum for my search result page and it works quite well.

The structure of the pricelist:

-pricelist (parent page)

   -priclistitem1 (child page)

   -priclistitem1 (child page)

   -priclistitem1 (child page)

   -priclistitem1 (child page)

   ........

The parent page is the main page and each pricelist item is a child page. They all are real pages with their own url.

Problem: If I search for a specific term and this term could be found in a child page, then I got the URL to the child page in the search result. This is what I do not want. I want to get only the url to the parent page in this case, because this is the page visible to the visitor.

The child pages are only parts of my pricelist.

I have searched the forum and found some similar entries but not exactly what I am looking for.

Can anyone point me into the right direction?

Link to comment
Share on other sites

you can hook into the URL render for the child pages by template, and change their URL - something like this (untested):

wire()->addHookBefore('Page::path', function($event) {
  $page = $event->object;
  
  if($page->template == 'pricelistitem') {
    $event->replace = true;
    $event->return = $page->parent->url;
  }
  
}); 
Link to comment
Share on other sites

Thank you Nicolas and Macrura for your suggestions!!!

Unfortunately I have forgotten to mention that the child pages are part of a Page table field on the parent page.

So here is my solution to search the Page table field with its "sub fields" from the child pages and output only the parent page in the search results if a search term was found in one (or more) child page(s).

This are the fields of the Page table field to search:

$pricelistfields = "servicepricelist.title|servicepricelist.description";

The Page table field name in my case is "servicepricelist" and I search in the "title" and the "description" field which are part of the child pages.

The next step is to exclude all the childpages in the search to prevent duplicate content.

$selector = "$searchfields~=$q, template!='pricelistitem', limit=50";  
$matches = $pages->find($selector);

I add "template!='pricelistitem'" to the search selector, because the template name of the child pages is "pricelistitem". So I get rid of all matches in the child pages directly. It only shows matches in the parent page.

Thats all!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...