WordPress.org

Ready to get started?Download WordPress

Forums

Getting posts of a specifc category (3 posts)

  1. shashank.tilwalli
    Member
    Posted 1 year ago #

    Hello Experts,

    I am trying to gets posts of specific categories.
    <?php
    $args = array( array('category__and' => array(9, 7)) );
    $acc_post = query_posts( $args );
    foreach( $acc_post as $post ) : ?>

    <?php the_title(); ?>

    <?php endforeach; ?>

    In the above code, I want to loop in through posts with category ID 9 AND 7.

    But the output returns all the posts irrespective of category. Am I doing something wrong?

    Reply

  2. SiteGround
    Member
    Posted 1 year ago #

    Hello,

    You should use the get_posts function to get all posts from the categories you want:

    <?php
       $args = array('category' => '9,7' );
       $myposts = get_posts( $args );
       foreach( $myposts as $post ) : ?>
       <?php the_title(); ?>
    <?php endforeach; ?>

    For more information on how get_posts work, check out this page: http://codex.wordpress.org/Template_Tags/get_posts

  3. alchymyth
    The Sweeper & Moderator
    Posted 1 year ago #

    alternatively, rewrite your code to use a 'while' loop:

    <?php
    $args = array( array('category__and' => array(9, 7)) );
    $acc_post = new WP_Query( $args );
    
    if( $acc_post->have_posts() ) while( $acc_post->have_posts() ) : $acc_post->the_post(); ?>
    
    <?php the_title(); ?>
    
    <?php endwhile; ?>

    http://codex.wordpress.org/Class_Reference/WP_Query

Topic Closed

This topic has been closed to new replies.

About this Topic