Skip to content

Instantly share code, notes, and snippets.

@BrElio
Forked from jchristopher/search-results.php
Created February 25, 2022 14:46
Show Gist options
  • Save BrElio/c5d0fb6ac3ec2fb5e40e766426785ecc to your computer and use it in GitHub Desktop.
Save BrElio/c5d0fb6ac3ec2fb5e40e766426785ecc to your computer and use it in GitHub Desktop.
Output SearchWP Live Ajax Search results grouped by Category taxonomy term
<?php
/**
* Search results are contained within a div.searchwp-live-search-results
* which you can style accordingly as you would any other element on your site
*
* Some base styles are output in wp_footer that do nothing but position the
* results container and apply a default transition, you can disable that by
* adding the following to your theme's functions.php:
*
* add_filter( 'searchwp_live_search_base_styles', '__return_false' );
*
* There is a separate stylesheet that is also enqueued that applies the default
* results theme (the visual styles) but you can disable that too by adding
* the following to your theme's functions.php:
*
* wp_dequeue_style( 'searchwp-live-search' );
*
* You can use ~/searchwp-live-search/assets/styles/style.css as a guide to customize
*/
if ( ! have_posts() ) : ?>
<p>No results</p>
<?php return; endif; ?>
<?php
global $post;
$grouped_results = [];
$no_term_results = [];
while ( have_posts() ) {
the_post();
$categories = get_the_terms( $post,'category' );
// Group by the first Category returned.
if ( ! empty( $categories ) && isset( $categories[0] ) ) {
// If this group doesn't exist yet, create it.
if ( ! array_key_exists( $categories[0]->term_id, $grouped_results ) ) {
$grouped_results[ $categories[0]->term_id ] = [
'term' => $categories[0],
'results' => [],
];
}
// Add this result to the group.
$grouped_results[ $categories[0]->term_id ]['results'][ $post->ID ] = get_post( $post->ID );
} else {
$no_term_results[ $post->ID ] = get_post( $post->ID );
}
}
// Output grouped results.
if ( ! empty( $grouped_results ) ) {
foreach ( $grouped_results as $grouped_result ) {
echo '<h3>' . esc_html( $grouped_result['term']->name ) . '</h3>';
foreach ( $grouped_result['results'] as $result ) {
?>
<div class="searchwp-live-search-result" role="option" id="" aria-selected="false">
<p>
<a href="<?php echo esc_url( get_permalink( $result->ID ) ); ?>">
<?php echo wp_kses_post( get_the_title( $result->ID ) ); ?> &raquo;
</a>
</p>
</div>
<?php
}
}
}
// Output ungrouped results.
if ( ! empty( $no_term_results ) ) {
foreach ( $no_term_results as $result ) {
?>
<div class="searchwp-live-search-result" role="option" id="" aria-selected="false">
<p>
<a href="<?php echo esc_url( get_permalink( $result->ID ) ); ?>">
<?php echo wp_kses_post( get_the_title( $result->ID ) ); ?> &raquo;
</a>
</p>
</div>
<?php
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment