Myat Htut
Myat Htut

Reputation: 487

How to retrieve Post from one Category in wordpress

I have problem in wordpress. I want to take post from only one category. For Example: I have 3 category name is 'a','b'and'c'.I want to show in my index page only 'a' category.Don't want to show other category's post. How can I solve???

Upvotes: 0

Views: 38

Answers (2)

helgatheviking
helgatheviking

Reputation: 26319

You want pre_get_posts.... which allows you to modify the query before it is run, which is obviously more efficient than running a new query on the blog page.

Adapted from the codex example for pre_get_posts

add_filter( 'pre_get_posts', 'so_single_cat_only_in_index' );
function so_single_cat_only_in_index( $query ){
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'category_name', 'a' );
    }
}

Upvotes: 0

Aibrean
Aibrean

Reputation: 6412

  <?php
         global $post;
         $args = array(
                        'numberposts' => 5,
                        'orderby' => 'post_date',
                        'order' => 'DESC',
                        'post_type' => 'post',
                        'post_status' => 'publish',
                        'category' => 27 //this is the ID for your category
          );
         $myposts = get_posts($args);
         foreach ($myposts as $post) {
         setup_postdata($post);?>
            <!--post loop -->
               <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>

    <?php }; ?>

Your array sets up the parameters of the display of posts. With this, it's pulling from one category (based on ID). If you wanted, you could go by name with 'category_name' => 'a'.

Upvotes: 1

Related Questions