phpWordpress

Displaying WordPress Custom Search Results

The Custom Search Template and The Page Template are vital to any complete WordPress Theme.

WordPress provides a powerful search functionality out of the box, but customizing the search results to fit your specific needs can enhance the user experience significantly. In this blog post, we will explore how to create and display custom search results in WordPress, including coding examples and best practices.

By default, WordPress uses the WP_Query class to fetch posts matching the search query. This is typically done in the search.php template file, where search results are displayed in a standard format. However, this behavior can be customized to display different post types, custom fields, or other specific elements.

2. Creating a Custom Search Form

First, let’s create a custom search form that we can place in our theme. You can add the following code to your theme’s header.php, sidebar.php, or wherever you want the search form to appear.

<form role="search" method="get" id="searchform" action="<?php echo home_url('/'); ?>">
    <div>
        <label for="s">Search:</label>
        <input type="text" value="<?php echo get_search_query(); ?>" name="s" id="s" />
        <input type="submit" id="searchsubmit" value="Search" />
    </div>
</form>

To create your own custom Search Page, you will need to create a Page template to include your search form and the information you want your users to see before they search your site.

3. Customizing the Search Results Page

Next, create or modify the search.php file in your theme. This file is responsible for displaying the search results. Here’s how you can customize it:

<?php
get_header();
global $wp_query;
?>
<section class="about-institute">
    <div class="container">
        <div class="row">
        <div class="col-md-12 welcome">
        
		<h3 class="panel-title inner-title"><?php echo $wp_query->found_posts; ?>
        <?php _e( 'Search Results Found For', 'locale' ); ?>: "<?php the_search_query(); ?>"</h3>
 
        <?php if ( have_posts() ) { ?>

            <ul class="search-result">

            <?php while ( have_posts() ) { the_post(); ?>

               <li>
                 <h3><a href="<?php echo get_permalink(); ?>">
                   <?php the_title();  ?>
                 </a></h3>
                 <?php  the_post_thumbnail('medium') ?>
                 <?php echo substr(get_the_excerpt(), 0,200); ?>
                 <div class="h-readmore"> <a href="<?php the_permalink(); ?>">Read More</a></div>
               </li>

            <?php } ?>

            </ul>
           <div class="pagination"><?php echo paginate_links(); ?></div>
        <?php } ?>
        
        </div>

    </div>
  </div>
</section>
<?php get_footer(); ?>

Explanation of the Code

  • Header and Footer: The template starts with including the header (get_header()) and ends with the footer (get_footer()).
  • Search Query Display: The search query is displayed at the top to inform users what they searched for.
  • Loop Through Results: The have_posts() function checks if there are any posts matching the search query. If there are, it loops through each post using the_post() and displays the title and excerpt.
  • Pagination: the_posts_pagination() provides navigation for multiple pages of search results.
  • No Results Message: If no results are found, a friendly message is displayed.

4. Customizing the Query for Specific Post Types

If you want to customize the search to include specific post types (like custom post types), you can modify the search query in your theme’s functions.php file.

function custom_search_query($query) {
    if ($query->is_search && !is_admin()) {
        // Specify the post types to include in search
        $query->set('post_type', array('post', 'page', 'your_custom_post_type'));
    }
    return $query;
}
add_filter('pre_get_posts', 'custom_search_query');

Explanation of the Code

  • Hook into pre_get_posts: This filter allows you to modify the query before it’s executed.
  • Check for Search Query: The function checks if it’s a search query and not in the admin area.
  • Set Post Types: The set() method specifies which post types to include in the search results.

5. Advanced Customization with Custom Fields

To search through custom fields (meta data), you can further customize your query. Here’s an example of how to do that:

function custom_search_meta_query($query) {
    if ($query->is_search && !is_admin()) {
        $meta_query = array(
            'relation' => 'OR',
            array(
                'key' => 'custom_field_key',
                'value' => $query->query_vars['s'],
                'compare' => 'LIKE'
            ),
        );

        // Include the existing post types
        $query->set('meta_query', $meta_query);
    }
    return $query;
}
add_filter('pre_get_posts', 'custom_search_meta_query');
function custom_search_meta_query($query) {
    if ($query->is_search && !is_admin()) {
        $meta_query = array(
            'relation' => 'OR',
            array(
                'key' => 'custom_field_key',
                'value' => $query->query_vars['s'],
                'compare' => 'LIKE'
            ),
        );

        // Include the existing post types
        $query->set('meta_query', $meta_query);
    }
    return $query;
}
add_filter('pre_get_posts', 'custom_search_meta_query');
  • How to Set Cookie Without Secure flag in IIS SERVER

    o ensure that cookies are set with the Secure flag in an IIS server, you need to configure your site to use this flag. The Secure flag ensures that cookies are only sent over HTTPS, improving the security of your web application by preventing them from being sent over unencrypted connections. Here’s how you can…

  • The “Access is denied” error when running wkhtmltopdf.exe on Windows

    Detailed Steps to Fix the “Access is Denied” Error 1. Ensure Correct Permissions on wkhtmltopdf.exe Grant Permissions to the User Running the Web Server: The IIS user (typically IUSR, IIS_IUSRS, or a custom user) needs to have Read & Execute permissions for wkhtmltopdf.exe.Steps:Navigate to C:\Program Files\wkhtmltopdf\bin\.Right-click wkhtmltopdf.exe and select Properties.Go to the Security tab.Click Edit…

  • How to Create an API in Node.js

    APIs (Application Programming Interfaces) are the backbone of modern software development, enabling communication between different systems. Node.js, a popular server-side platform, makes API creation seamless and scalable. This guide walks you through the steps to create a simple API using Node.js. Prerequisites Before starting, ensure you have the following installed: Node.js (You can download it…

  • Node.js File Upload: A Complete Guide

    Uploading files is a common task in web applications, whether it’s images, documents, or other types of data. Node.js, known for its asynchronous and non-blocking nature, offers an efficient way to handle file uploads. In this guide, we will explore how to implement file upload functionality in Node.js using the popular express framework and the…

  • Step-by-Step Guide: How to Install Magento 2 on Windows

    Magento 2 is a powerful eCommerce platform known for its flexibility and scalability. While it’s commonly hosted on Linux servers, you can also set it up on Windows for development and testing purposes. In this guide, we’ll walk you through the installation process of Magento 2 on a Windows machine, ensuring you have a solid…

  • Understanding __construct() and __destruct() Methods in PHP Classes

    Understanding __construct() and __destruct() Methods in a PHP Class In object-oriented programming (OOP), classes form the blueprint for creating objects. PHP, being an object-oriented language, offers special methods known as magic methods that allow developers to handle object initialization and cleanup. Among these methods, __construct() and __destruct() are two of the most important. These methods…

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button