Skip to content

Instantly share code, notes, and snippets.

@jonathanlaf
Created March 25, 2021 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathanlaf/5f57436ad1129dbbafac1484f981a111 to your computer and use it in GitHub Desktop.
Save jonathanlaf/5f57436ad1129dbbafac1484f981a111 to your computer and use it in GitHub Desktop.
Relevanssi search date through content and through published date
// Inspired by : https://www.relevanssi.com/knowledge-base/natural-language-date-queries/?replytocom=264649#respond
add_filter('relevanssi_modify_wp_query', 'rlv_date_query');
function rlv_date_query($query)
{
if (substr($query->query_vars['s'], 0, 10) === "published:") {
// Remove "published:" from search string.
$query->query_vars['s'] = substr($query->query_vars['s'], 10);
// If The query string is a year... (We check that it's an integer between 1900 and current year)
if ((int) $query->query_vars['s'] > 1900 && (int) $query->query_vars['s'] <= date("Y")) {
$date_query = [
'column' => 'post_date',
'year' => $query->query_vars['s'],
];
$query->set('date_query', $date_query);
// Empty search. (@TODO removed consumed part of the search string so we can search for something at a date.)
$query->query_vars['s'] = '';
}
// If the actual search string convert to a timestamp!
// Support almost any "Natural language" date with or without year.
else if ($time = strtotime($query->query_vars['s'])) {
$year = date('Y', $time);
$use_year = strpos($query->query_vars['s'], $year) !== false;
$month = date('m', $time);
$day = date('d', $time);
$date_query = [
'column' => 'post_date',
'month' => $month,
'day' => $day,
];
if ($use_year) {
$date_query['year'] = $year;
}
$query->set('date_query', $date_query);
// Empty search. (@TODO removed consumed part of the search string so we can search for something at a date.)
$query->query_vars['s'] = '';
}
}
return $query;
}
<!-- Heading of the page -->
<?php
if (substr($_GET['s'], 0, 10) === "published:") {
echo '<span>' . __("Search articles and books published on:") . substr($_GET['s'], 10) . '</span>';
} else {
echo '<span>' . __("Search results for:") . $_GET['s'] . '</span>';
}
?>
<!-- Under the search form -->
<?php
if (strtotime($_GET['s'])) {
echo __("Not the result you where expecting? We’ve detected that you might have entered a date. Would you like to ") . ' ' . '<a href="' . get_site_url() . '/?s=published:' . $_GET['s'] . '">' . __('search by publication date') . '</a> '.__('instead of content ?');
} else {
echo __("Not happy with the results? Please try another search.");
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment