1

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:

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

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

<?php endwhile; ?>    

<!-- PAGINATION here below -->

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

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;
}

add_filter('pre_get_posts','search_only_posts');

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.

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.