how to prevent query_posts() to change status from home to category/archive? (6 posts)

  1. normadize
    Posted 2 years ago #

    Hi all,

    In my home.php I am calling query_posts("cat=8") to display posts only from one category on the home page. This works fine but the problem is that the status of the posts is not "home" but "category" and "archive". This is a problem for content.php which is checking the status using is_home(), and this fails ... although they are on the home page.

    Is there a way to prevent this and maintain "home" status for the posts?

    Currently I am hacking it by having the following right after query_posts():

    global $wp_query;
    $wp_query->is_home = true;

    Which forces the is_home flag. Is there a more elegant solution?

    It's hard to call this a bug, but I think it is at least unexpected behaviour.

  2. Michael
    Part-Time Forum Moderator
    Posted 2 years ago #

    a: use at least wp_reset_query(); at the end of the loop with your custom query;


    or better, use WP_Query() for the custom loop;

  3. normadize
    Posted 2 years ago #

    But that doesn't help the problem, which is that the posts are seen as NOT being in "home", i.e. is_home() returns false. The fact that "cat=8" is used triggers the query to have is_home = false, instead of true.

  4. Michael
    Part-Time Forum Moderator
    Posted 2 years ago #


    instead of:



    global $query_string; query_posts( $query_string . "&cat=8");

  5. normadize
    Posted 2 years ago #

    Thanks for trying to help, but it doesn't work. The fact that there is "cat=8" triggers the query to set $wp_query->is_home to false. The solution I posted works, but is ugly (it forces the flag back to true), and I think this is all unexpected behaviour, if not a bug.

  6. Michael
    Part-Time Forum Moderator
    Posted 2 years ago #

    another possibility:

    add this into functions.php of your theme:

    function include_category( $query ) {
        if ( $query->is_home() && $query->is_main_query() ) {
            $query->set( 'cat', '8' );
    add_action( 'pre_get_posts', 'include_category' );

Topic Closed

This topic has been closed to new replies.

About this Topic