How to exclude WordPress pages from search engine results using the PHP function

By default, WordPress displays all posts and pages in the search results. Some WordPress pages, such as the checkout, thank you, and profile pages, should be excluded from the search results. This article demonstrates how to use the PHP function to exclude WordPress pages from search results.

Excluding WordPress pages from search result

Always perform a backup before you make any changes to the theme files. If you break any codes, it will be easier to revert your site to its last good known state. Alternatively, you could also create a child theme. Read this link on how to create a child theme: https://www.a2hosting.com/blog/wordpress-child-theme/  

Follow the steps below to edit your Theme setting file to exclude pages from search in WordPress:

  1. Log in to your WordPress site with an administrator account.
  2. On the Dashboard in the left sidebar, click Appearance, and then click Theme Editor:

  3. On the Theme Editor , select the Theme you want to edit from the dropdown:

  4. The files for this selected theme are listed on the right column under Theme Files. Click on the file named “functions.php”:

  5. Insert the following code to the end of functions.php file and click Update File Button to save the changes:

     

    function SearchFilter($query) {
    
            if ($query->is_search) {
    
                      $query->set('post_type', 'post');
    
              }
    
          return $query;
    
     }
    
    add_filter('pre_get_posts','SearchFilter');

     

     

  6. The code above will exclude pages from WordPress search results. The pre_get_posts hook filters the search result. In this code the filter condition is set post_type to post , which limits search to only posts from the WordPress site

     

Get Managed WordPress Hosting

Article Details

Other Articles in This Category

Show More

Did you find this article helpful? Then you'll love our support. Experience the A2 Hosting difference today and get a pre-secured, pre-optimized website. Check out our web hosting plans today.

We use cookies to personalize the website for you and to analyze the use of our website. You consent to this by clicking on "I consent" or by continuing your use of this website. Further information about cookies can be found in our Privacy Policy.