Skip to content

Instantly share code, notes, and snippets.

@benpearson
Created January 7, 2025 03:57
Show Gist options
  • Save benpearson/57c54b7a4ccb344d8c228e9e7ee92e27 to your computer and use it in GitHub Desktop.
Save benpearson/57c54b7a4ccb344d8c228e9e7ee92e27 to your computer and use it in GitHub Desktop.
WordPress: Search template using Search WP custom query
<?php
/**
* Search results
*
* Example of a custom query using Search WP. Note this only needed if you need a custom query.
*/
get_header();
$swp_query = new SWP_Query([
's' => get_search_query(),
'engine' => 'default',
]);
?>
<?php if ($swp_query->have_posts()) : ?>
<?= esc_html($wp_query->found_posts) ?> results found for <span>"<?= esc_html(get_search_query()) ?>"</span>
<?php the_posts_pagination(); ?>
<?php while ($swp_query->have_posts()) : ?>
<?php
$swp_query->the_post();
$search_result_excerpt = get_the_excerpt();
?>
<a href="<?php the_permalink(); ?>" class="">
<?php the_title(); ?>
</a>
<?php if ($search_result_excerpt) : ?>
<?= $search_result_excerpt ?>
<?php endif; ?>
<a href="<?php the_permalink() ?>" class="">
<?php the_permalink() ?>
</a>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php the_posts_pagination(); ?>
<?php else : ?>
No results found for <span>"<?php echo esc_html(get_search_query()) ?>"</span>.
<?php endif; ?>
<?php get_footer(); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment