0
0
0906ddd2021-08-31 11:43:58
WordPress
0906ddd, 2021-08-31 11:43:58

How to add a condition to the search?

now I'm looking only in the blog ,
but if I add a criterion for news or something else (it doesn't matter)
like this
'post_type' => array('news', 'blog' )

then another template is needed for news ( get_template_part( 'template- parts/news-item', get_post_format() );

not get_template_part( 'template-parts/blog-item', get_post_format() );

<section class="search">
  <div class="container">
      <h3 class="search__title"><?php echo get_search_query(); ?></strong>
      </h3>
      <div class="search__inner">
          <?php
              $search = new WP_Query( array(
                  'post_type' => array('blog'),
                  'posts_per_page' => -1,
                  's' => get_search_query()
              ));
          if( $search->have_posts() ) : while ( $search->have_posts() ) : $search->the_post(); 
              get_template_part( 'template-parts/blog-item', get_post_format() );
          ?>

          <?php endwhile;
          else:
               echo '<div class="msg-page">'.$translate[$lang]['search_error'].'</div>';
          endif; ?>
      </div>
  </div>
</section>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Zolin, 2021-08-31
@0906ddd

You can check post_type in a loop before including the template like so:

if ( get_post_type() === 'news' ) {
  get_template_part( 'template-parts/news-item', get_post_format() );
} else {
  get_template_part( 'template-parts/blog-item', get_post_format() );
}

Another good example from practice: it checks for the presence of the archive-{post-type}.php template in the templates/archive/ folder , if it is not there, the base archive-simple.php is included
$post_type = get_post_type();

if ( file_exists( get_theme_file_path( 'templates/archive/archive-' . $post_type . '.php' ) ) ) {
  get_template_part( 'templates/archive/archive-' . $post_type );
} else {
  get_template_part( 'templates/archive/archive-simple' );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question