0

I'm currently running WordPress 4.5 with a WooTheme called The Morning After. I decided to change a few things here and there, but encountered some issues regarding the posts_per_page argument used in the WP_Query object. The intention is to show more than one post (3 or 4 posts) and ignore the category Featured articles.

$args = array(
    'posts_per_page'   => 2,
    'category__not_in' => get_cat_ID('Featured articles')
);

$query = new WP_Query($args);

while ( $query->have_posts() ) { 
    $query->the_post();
    echo '<li>' . get_the_title() . '</li>';
};

What am I doing wrong? Result is 4 posts including the posts that are in the category Featured articles.

4
  • it should be WP_Query , i assume that's mistake you have done while asking
    – bravokeyl
    Apr 23, 2016 at 17:42
  • Do you want to alter main loop or adding secondary loop ?
    – bravokeyl
    Apr 23, 2016 at 17:43
  • Specify post type inside you query
    – vol4ikman
    Apr 23, 2016 at 18:02
  • Yes it was a mistake while asking. The WP_Query is, by default, using post_type=post. This is the main loop I altered.
    – empec
    Apr 23, 2016 at 20:35

1 Answer 1

0

If you are altering main query then use pre_get_posts filter instead of WP_Query.

add_action('pre_get_posts','wpse224610_alter_query');
function wpse224610_alter_query($query){
      $cat_id = get_cat_ID('Featured articles');
      $exclude_cat_id = -$cat_id;
      if( !is_admin() && $query->is_main_query() ){
         $query->set( 'cat', $exclude_cat_id );
         $query->set( 'posts_per_page', 4 );
      }
}

And the main loop will be

if( have_posts() ):
    while( have_posts() ): the_post();
       //The loop
    endwhile;
endif;

Check the return value of $cat_id , is it 0 or Featured articles category id ? check whether you spelled category name correctly as it is in the admin ?

From your code i assume you are trying to do secondary loop but as you told it's main loop , use above mentioned filter.

Read more

4
  • Perhaps I'm the one being confused what the main loop exactly is. I thought it was the main loop because it is the first loop in that file, which is home.php. Perhaps the WP_Query in wp-includes/functions.php is considered the main loop? I'll read the url you attached and see how it goes.
    – empec
    Apr 24, 2016 at 7:23
  • check this also wordpress.stackexchange.com/q/1753/43098
    – bravokeyl
    Apr 24, 2016 at 7:26
  • It is running local.
    – empec
    Apr 24, 2016 at 7:29
  • Thank you so much, it was indeed not the main loop that I should have altered. But instead just use get_posts($args). Now it works.
    – empec
    Apr 24, 2016 at 7:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.