Support » Fixing WordPress » Getting posts of a specifc category

  • 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

Viewing 2 replies - 1 through 2 (of 2 total)
  • 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

    Michael

    (@alchymyth)

    Forum Moderator

    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

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Getting posts of a specifc category’ is closed to new replies.