1

Regarding wordpress.org - sticky posts are displayed at the top but they also appear again in the loop.

For the main loop on my homepage I want to display the sticky posts at the top BUT I don't want the post to appear again in the loop, otherwise it appears redundant to the visitor.

Problem with the below code is they remove the sticky post from the top.
I want to KEEP the sticky posts at the top
but REMOVE/EXCLUDE it from the loop. Is this possible?

CODE A: This removes sticky post from top

function mango($query){
if ( $query->is_home() && $query->is_main_query() && !is_admin() ) {
    $query->set( 'ignore_sticky_posts', true );
    }
}
add_action( 'pre_get_posts', 'mango' );

CODE B: This removes sticky post from both the top AND loop

function mango($query){
if ( $query->is_home() && $query->is_main_query() && !is_admin() ) {
    $query->set( 'post__not_in', get_option( 'sticky_posts' ) );
    }
}
add_action( 'pre_get_posts', 'mango' );

1 Answer 1

1

The sticky posts are prepended on the first paginated part of the home page, so try this:

add_action( 'pre_get_posts', function( $q ) 
{
    if ( $q->is_home() && $q->is_main_query() && $q->get( 'paged' ) > 1 )
        $q->set( 'post__not_in', get_option( 'sticky_posts' ) );

} );

to remove it from the other paginated parts of the home page.

2
  • It works!! You are a genius, I tell ya! Just one question. Does it matter where I paste this in the functions.php file ?
    – stadisco
    Jul 16, 2015 at 3:37
  • great - you should be able to put this anywhere in the functions.php file (global scope) or better yet, create a plugin from this. @leko
    – birgire
    Jul 16, 2015 at 3:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.