Last active
March 5, 2025 16:34
-
-
Save bdeleasa/3e5ba98fe039fe48a031bf3ecdbea732 to your computer and use it in GitHub Desktop.
Change Drupal 10 search results to sort in date order DESC.
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 | |
/** | |
* Implements hook_query_TAG_alter(). | |
* | |
* Orders the search results by the changed date in descending order. | |
* | |
* @param \Drupal\Core\Database\Query\AlterableInterface $query | |
*/ | |
function mymodule_query_search_node_search_alter(\Drupal\Core\Database\Query\AlterableInterface $query): void | |
{ | |
$query->orderBy('n.created', 'DESC'); | |
} | |
/** | |
* Implements hook_preprocess_search_result(). | |
* | |
* Preprocesses variables for the search result template. | |
* | |
* We want to show the created date and not the updated date for nodes | |
* that are in search results. We're adding a new variable to | |
* use in the search-result.html.twig template. | |
* | |
* @param array $variables | |
* The variables array for the search result template. | |
*/ | |
function mymodule_preprocess_search_result(array &$variables): void { | |
if (isset($variables['result'])) { | |
$node = $variables['result']['node']; | |
if ($node) { | |
$variables['created_date'] = \Drupal::service('date.formatter')->format($node->getCreatedTime(), 'long'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment