Snippets – Viki Johnson https://work.vikijohnson.com Digital Business Solutions Fri, 14 Jul 2023 15:24:06 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://work.vikijohnson.com/wp-content/uploads/2023/05/Viki-site-icon-150x150.png Snippets – Viki Johnson https://work.vikijohnson.com 32 32 Exclude Pages From Search Results in WordPress — Only Show Posts or Products https://work.vikijohnson.com/exclude-pages-from-search-results-in-wordpress-only-show-posts-or-products/ https://work.vikijohnson.com/exclude-pages-from-search-results-in-wordpress-only-show-posts-or-products/#respond Fri, 14 Jul 2023 15:24:06 +0000 https://portfolio.vikijohnson.com/?p=853 If you have a WordPress website, you may have noticed that by default, WordPress includes all types of content such as posts, products, pages, image file URLs, PDF file URLs, and more in search results. This can be a turnoff for your site users and make your search results page look very messy. To limit the search results to only display posts, you can copy and paste the code snippet below into your theme’s function.php file.

However, it is recommended that you create a child theme and paste the code into the function.php file of the child theme instead. This is to avoid breaking anything on your website when you try to edit the original theme. Furthermore, if you update the original theme in the future, your code will remain intact in the child theme. If you paste the code in the original theme, it might be overwritten whenever you update it.

If you do not know how to create a child theme, don’t worry. Watch the video below and follow it step-by-step.

if (!is_admin()) {
    function wpb_search_filter($query) {
        if ($query->is_search) {
            $query->set('post_type', 'post');
        }
        return $query;
    }
    add_filter('pre_get_posts','wpb_search_filter');
}
Video by Ferdy Korpershoek
]]>
https://work.vikijohnson.com/exclude-pages-from-search-results-in-wordpress-only-show-posts-or-products/feed/ 0