using in_category rather than query_posts in wordpress

In wordpress I have a page template called news that I want to display all the posts from one category – ‘News’. I don’t want to use the category.php because there is a massive blog on the site already.

 query_posts('cat=145');  
 while ( have_posts() ) : the_post();
 //do something
 endwhile; 

Works fine but I have read that query_posts has drawbacks (like speed)

Read More

I tried doing this but it just showed me nothing:

while ( have_posts() ) : the_post();
if ( in_category( '145' ) ) : //also tried 'News'
//do something

Why doesn’t’ in_category work here?

Related posts

4 comments

  1. please try this code:

    $args = array('post_type' => 'post',
            'tax_query' => array(
                    array(
                            'taxonomy' => 'category',
                            'field'    => 'slug',
                            'terms'    => 'news'  // please pass here you news category slugs 
                        ),
                    )
            );
    
        $loop = new WP_Query( $args );
        while ( $loop->have_posts() ) : $loop->the_post();
            print_r($post);
        endwhile;
    
        wp_reset_postdata();
    
  2. You could WP Query for achieving your requirement.

    Documentation: https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
    Example:

    <?php
    $args = array(
      'cat' => 145,
    );
    $the_query = new WP_Query( $args ); ?>
    
    <?php if ( $the_query->have_posts() ) : ?>
    
      <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <h2><?php the_title(); ?></h2>
      <?php endwhile; ?>
    
      <?php wp_reset_postdata(); ?>
    
    <?php endif; ?>
    
  3. Try to use get_posts() function:

    $get_p_args = array('category'=> 145,'posts_per_page'=>-1);
    
    $myposts = get_posts( $get_p_args );
    foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
        <div>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </div>
    <?php endforeach; 
    wp_reset_postdata();?>
    
  4. Try this:

    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    global $wp_query;
    $args = array_merge( $wp_query->query_vars, array(
        'post_type' => 'post', // You can add a custom post type if you like
        'paged' => $paged,
        'posts_per_page' => 6, // limit of posts
        'post_status' => 'publish',
        'orderby' => 'publish_date',
        'order' => 'DESC',
        'lang' => 'en', // use language slug in the query
    ) );
    query_posts( $args );
    

Comments are closed.