Where should I update_options in a theme?

I am designing a theme where the home page (i.e. is_home()) should only display the latest blog post. I want to do something like $wp_query->update_option('posts_per_page', 1) every time I am on the home page. All other pages that display posts (like archives) should just follow the user defined option.

This seems a bit unnecessary to do every single time since the option should just be set once, right? Is it possible within The Loop to just ignore the user-set option of posts_per_page and force have_posts() to just be set to one post?

Read More

In general, where should this kind of “set-it-once” stuff go? I don’t really think it should be a plug-in because it is theme specific. I also don’t want to mess with the user’s options which is why update_option isn’t the best choice for this problem.

Related posts

Leave a Reply

3 comments

  1. Alternate approach (if you want/need to keep this in functions.php and go via hooks instead of modifying template) would be something like this:

    add_action( 'pre_get_posts', 'pre_get_posts_home' );
    
    function pre_get_posts_home( $query ) {
    
        global $wp_query;
    
        if( $wp_query == $query && $query->is_home )
            $query->set( 'posts_per_page', 1 );
    }
    
  2. posts_per_page should be set once the at settings reading panel, and acts as a general option unless defined else using query_posts() for example if you want your homepage to display only one then the place this code above your loop:

    if (is_home()){ // conditional check for homepage
        global $query_string;
        parse_str( $query_string, $args );
        $args['posts_per_page'] = 1;
        query_posts( $args );
    }