0

I need to limit the posts shown in WordPress front page on the first page only. The reason for it is a sticky post which breaks my layout and the number of total post set up in default WP setting.

I found this function for functions.php but it appears to not work.

Can you help me to fix it? I prefer a functions.php change.

I wonder if it's not working because post with this snippet is really new.

add_action( 'pre_get_posts', 'sk_change_posts_per_page' );

/**
 * Change Posts Per Page for first page of Posts page
 *
 * @param object $query data
 */
function sk_change_posts_per_page( $query ) {

  if( $query->is_main_query() && ! is_admin() && is_home() && ! is_paged() ) {
    $query->set( 'posts_per_page', '2' );
  }

}

Source

0

The pre_get_posts runs before WP_Query has been setup. Some template tags and conditional functions that rely on WP_Query will not work. you will need to work directly with the query vars, which are passed to the pre_get_posts hook as an argument.

See the more information on the following pages: pre_get_posts and using pre_get_posts

Try using the following code.

add_action( 'pre_get_posts', 'sk_change_posts_per_page' );

/**
 * Change Posts Per Page for first page of Posts page
 *
 * @param object $query data
 */
function sk_change_posts_per_page( $query ) {

  if( $query->is_main_query() && ! is_admin() && $query->is_home() && ! $query->is_paged() ) {
    $query->set( 'posts_per_page', '2' );
  }

}
  • just tested your code in functions.php . no effect. thx for the try. – Nicy Jun 15 '14 at 1:15
  • @Nicy Which theme are you using? Have you developed custom page template to display posts on the front page? – Vinod Dalvi Jun 15 '14 at 4:37
  • Its a thumbnail image gallery not real posts. Ive tested an other code it works but on all pages not only at the first. i can find it again – Nicy Jun 15 '14 at 14:25
  • also maybe an other snippet could be incompatible with your code`? for example: function filter_posts() { global $wp_query; if(is_home()) { $wp_query->set('category__not_in',array(41558,42051,42054)); // ID der Kategorie to exclude } } – Nicy Jun 15 '14 at 17:38
  • ive also tested this code not work: wordpress.stackexchange.com/questions/194/… – Nicy Jun 15 '14 at 17:43

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.