0

I want to exclude category posts from index & archive pages, so I wrote this script in functions.php:

function exclude_category($query) {
    if ( $query->is_home() || $query->is_archive() ) {
        $query->set( 'cat', '-33799' );
    }
    return $query;
}
add_filter('pre_get_posts', 'exclude_category');

Everything works fine till here, but I need to show the latest posts from this category in a box on all pages:

$args = array ( 'category' => "33799", 'posts_per_page' => 2 );
$recentposts = get_posts( $args );
foreach ( $recentposts as $post ) : setup_postdata( $post ); 
    if ( get_post_meta( $post->ID, "news_thumb", TRUE ) ) {
        $img = get_post_custom_values( "news_thumb", $post->ID );
    } else {
        $img = 'images/no_pic.jpg';  
    }
    if ( get_post_meta( $post->ID, "news_short_content", TRUE ) ) {
        $content = get_post_custom_values( "news_short_content", $post->ID );
    } else {
        $content = '';   
    }           
    ?>
    SHOW_SOMETHING_IN_LOOP
    <?php 
endforeach;

When I add this script to header.php, I get the wrong output. I can understand why this is happening, because I excluded the category in the query, but how can I fix this?

  • if ( $query->is_home() || $query->is_archive() ) should be if (!is_admin() && $query->is_main_query() && ( $query->is_home() || $query->is_archive() ) ) – Pieter Goosen Oct 27 '15 at 10:16
  • @PieterGoosen thanks a lot ! problem solved , but i can't understand what happened? when this function return true why we should use it in condition ? and why problem solved , can you help me to find out this question please ? i read this article : link but still can't understand :) – user3325376 Oct 27 '15 at 12:23
  • is_main_query() only returns true in the main query. pre_get_posts alters all queries back end and front end, there is no destingtion between queries. Because you only want to target the main query with pre_get_posts, and not all the other queries, you need exclude all other queries by checking if the current query is the main query. – Pieter Goosen Oct 27 '15 at 12:41
0

Pieter Goosen solved the issue with with this suggestion.

if ( $query->is_home() || $query->is_archive() )

Should be:

if (!is_admin() && $query->is_main_query() && ( $query->is_home() || $query->is_archive() ) )

Then explains why this solution worked:

is_main_query() only returns true in the main query. pre_get_posts alters all queries back end and front end, there is no designation between queries. Because you only want to target the main query with pre_get_posts, and not all the other queries, you need exclude all other queries by checking if the current query is the main query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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