I have a WordPress site with a custom search bar on my homepage, provided by the Apus service search bar plugin. When users search for services, the results currently display the titles of the services. However, I want to modify the search results so that they show the categories of the employers associated with these services instead of the service titles.
Search Bar: Implemented using the Apus service search bar plugin.
Search Results: Display the titles of the services by default.
Employer Categories: A custom taxonomy called employer_category
I understand that I need to modify the template file that renders the search results. Here is my current approach, but I’m unsure how to fetch and display the employer categories correctly.
<search.php>
<?php
/**
* The template for displaying archive pages (services).
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/
*
* @package YourThemeName
*/
get_header();
?>
<section id="primary" class="content-area">
<main id="main" class="site-main">
<?php if ( have_posts() ) : ?>
<header class="page-header">
<h1 class="page-title"><?php printf( esc_html__( 'Search Results for: %s', 'your-theme-text-domain' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
</header>
<div class="search-results">
<?php while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class( 'search-result-item' ); ?>>
<?php
// Fetch the employer categories
$employer_categories = get_the_terms( get_the_ID(), 'employer_category' );
if ( ! empty( $employer_categories ) && ! is_wp_error( $employer_categories ) ) :
foreach ( $employer_categories as $category ) : ?>
<h2 class="search-result-title"><?php echo esc_html( $category->name ); ?></h2>
<?php endforeach;
else : ?>
<h2 class="search-result-title"><?php esc_html_e( 'No categories found', 'your-theme-text-domain' ); ?></h2>
<?php endif; ?>
<!-- Other result information -->
</article><!-- #post-<?php the_ID(); ?> -->
<?php endwhile; ?>
</div><!-- .search-results -->
<?php the_posts_navigation(); ?>
<?php else : ?>
<p><?php esc_html_e( 'No results found. Please try again with different keywords.', 'your-theme-text-domain' ); ?></p>
<?php endif; ?>
</main><!-- #main -->
</section><!-- #primary -->
<?php
get_sidebar();
get_footer();
?>
Anas Mourabi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.