1

I am trying to display the search result based on custom post type in sections. and if no search result for post type I do not want to display that section label . here the problem with this code is $post_query in custom_has_posts() function, the query containing all the post types instead of the one I have passed in function call .

search.php page

<?php if ( have_posts() ) : ?>
    <?php $post_types = get_post_types(array('public' => true, 'exclude_from_search' => false), 'objects'); ?>
        <?php foreach( $post_types as $post_type ): ?>
              <?php if ( !in_array($post_type->name, array('page', 'menu', 'nav_menu_item', 'custom_css', 'customize_changeset', 'revision') ) ): ?>
              <div class="postcards">
                 <?php if ( custom_has_posts($post_type->name) > 0 ) {?>
                     <h4><?php echo $post_type->label; ?></h4>
                 <?php } ?>
              <?php while ( have_posts() ) : the_post(); ?>
                        <?php if ( $post_type->name == get_post_type() ): ?>
                        <div class="grid__item  postcard">
                            <?php
                            /*
                             * Include the Post-Format-specific template for the content.
                             * If you want to override this in a child theme, then include a file
                             * called content-___.php (where ___ is the Post Format name) and that will be used instead.
                             */
                            get_template_part( 'template-parts/content', get_post_format() );
                            ?>
                            </div>
                        <?php endif; ?>
                        <?php endwhile; ?>
              <?php } ?>
        <?php } ?>
  <?php endif; ?>

custom_has_posts() function

function custom_has_posts($post_type){
   // wp_reset_postdata();
   // $post_query = null;
    //unset($post_query);
   // wp_reset_query();
    $post_query = new WP_Query( array( 'post_type' => $post_type, 'posts_per_page' => -1, 's' => $_GET['s'] ) );
    $count =  $post_query->post_count;
    wp_reset_postdata();
    $post_query = null;
    unset($post_query);
    wp_reset_query();
    return $count;
}
7

Your Answer

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

Browse other questions tagged or ask your own question.