I'm trying to display only posts in my search result page.

so I just added the code below in functions.php:

function is_type_page() {

    global $post;

    // Check if the current post is a page.
    if ($post->post_type == 'page') {
        return true;
    } else {
        return false;

and this condition below in search.php:

<?php while ( have_posts() ) : the_post(); ?>
    <?php if (is_type_page()) continue; ?>

I can get successfully the posts but the problem is that pagination is not displayed correctly , it shows me many blank pages, it seems like it still quering both posts and pages ( just hiding pages content)

How can I fix that?

This is my code:

    while (have_posts()):
    if (is_type_page())

<div class="search-result">
    <div class="image-content">
            if (has_post_thumbnail()) {
            } else {
        <img src="<?php bloginfo('template_directory'); ?>/assets/images/image-not-found.png" />
    <div class="text-content">
        <h4 style="">
            <?php the_title(); ?>
            <?php the_excerpt(); ?>

<?php endwhile; ?>    

<!-- PAGINATION here below -->

<div class="nav-previous alignleft">
   <?php previous_posts_link('Older posts'); ?>
<div class="nav-next alignright">
    <?php next_posts_link('Newer posts'); ?>

The pagination isn't working correctly because it assumes you want to paginate all results. You are simply hiding pages, by which time it's too late to adjust the pagination.

To fix this, you need to alter the query using the pre_get_posts filter. For example:

function search_only_posts($query) {
    if($query->is_search) {
        $query->set('post_type', 'post');
    return $query;


You may need to add various checks like is_admin() or is_main_query() so that you only change the behaviour on the front-end of the site, and not the admin area.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.