Forums

Basic question re: get posts in a category (2 posts)

  1. calex3710
    Member
    Posted 7 months ago #

    Hi -- relative newbie to this, so forgive me for asking a question I know is basic, but I had a question about how to bring in posts that have been given a certain category. I can't find anything straightforward about this in the codex, but what is the php to bring in posts with the category of 'example' to a certain template/page?

    Thank you for your time.

  2. alchymyth
    The Sweeper
    Posted 7 months ago #

    example using WP_Query():

    <?php $example_query = new WP_Query(array('category-name' => 'example'));
    if( $example_query->have_posts() ) :
    while( $example_query->have_posts() ) :
    $example_query->the_post();
    /*whatever output you want*/
    endwhile;
    else:
    echo 'no posts for category "example"'; ?>
    endif; wp_reset_postdata(); ?>

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

    ---
    alternative code using get_posts():

    <?php $example_posts = get_posts('category_name=example');
    if( $example_posts ) foreach( $example_posts as $post ) {
    setup_postdata($post);
    /*whatever output you want*/
    }
    wp_reset_postdata(); ?>

    http://codex.wordpress.org/Template_Tags/get_posts

Reply

You must log in to post.

About this Topic