WordPress.org

Ready to get started?Download WordPress

Forums

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

  1. normadize
    Member
    Posted 1 year 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. alchymyth
    The Sweeper & Moderator
    Posted 1 year ago #

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

    http://codex.wordpress.org/Function_Reference/wp_reset_query
    http://codex.wordpress.org/Function_Reference/query_posts#Usage

    or better, use WP_Query() for the custom loop;
    http://codex.wordpress.org/Class_Reference/WP_Query

  3. normadize
    Member
    Posted 1 year 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. alchymyth
    The Sweeper & Moderator
    Posted 1 year ago #

    http://codex.wordpress.org/Function_Reference/query_posts#Preserving_Existing_Query_Parameters

    instead of:

    query_posts("cat=8");

    try:

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

  5. normadize
    Member
    Posted 1 year 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. alchymyth
    The Sweeper & Moderator
    Posted 1 year ago #

    another possibility:
    http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts

    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