here is the deal...

I got hold of this piece of code to change the default post type shown on my TwentyTen child theme's homepage. It works like a charm when I add this code to the functions.php file, but I would like to also limit the number of posts to 1 (or 2) instead of the default 10 as in "Settings" section.

What can I add to the code below so that it display only 1 (or 2) Tours?

add_action( 'pre_get_posts', 'add_tours_post_type_to_query' );
function add_tours_post_type_to_query( $query ) {
if ( is_home() && $query->is_main_query() )
$query->set( 'post_type', array( 'tours' ) );
return $query;
}    

I hope I can get some help here! Many thanks.

UPDATE: I pasting here how I manage to filter by category as well...

add_action( 'pre_get_posts', 'add_tours_post_type_to_query' );

function add_tours_post_type_to_query( $query ) {

if ( is_home() && $query->is_main_query() ) {
    $query->set( 'posts_per_page', 1 );
    $query->set( 'category_name', 'featured_tour' );
    $query->set( 'post_type', array( 'tours' ) );
}
return $query;
}

Many thanks

有帮助吗?

解决方案

This should do the trick:

add_action( 'pre_get_posts', 'add_tours_post_type_to_query' );

function add_tours_post_type_to_query( $query ) {

  if ( is_home() && $query->is_main_query() ){
    $query->set( 'post_type', array( 'tours' ) );
    $query->set( 'posts_per_page', 1 );
  }

  return $query;
}

For the future the Codex can be your friend. Exactly this is explained there.

其他提示

See the posts_per_page query var.

add_action( 'pre_get_posts', 'add_tours_post_type_to_query' );

function add_tours_post_type_to_query( $query ) {

    if ( is_home() && $query->is_main_query() ) {
        $query->set( 'post_type', array( 'tours' ) );
        $query->set( 'posts_per_page', 2 );
    }

    return $query;
}
许可以下: CC-BY-SA归因
scroll top