0

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

1

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.

| improve this answer | |
  • Beat me by 12 secs. ;) +1 – tfrommen Dec 2 '14 at 22:57
  • Awesome! you make it look so simple... I'm a bit of a beginner but getting my way into it. Can we filter by category by any chance? i.e. Featured Tours – phg Dec 2 '14 at 23:08
  • This is why I added the link to the source. Just scroll a liiittle bit upwards. Also for the future: Either edit your original question or ask a new one if you have follow up questions. And use search - these are pretty standard issues. – kraftner Dec 3 '14 at 9:24
0

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;
}
| improve this answer | |
  • Awesome! you make it look so simple... I'm a bit of a beginner but getting my way into it. Can we filter by category by any chance? i.e. Featured Tours – phg Dec 2 '14 at 23:10

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.