• Resolved lisajwells

    (@lisajwells)


    My front page displays posts, limited to 5 per page, with a sticky post at the top. When I go to the 2nd page, the sticky post is also at the top of the 2nd page, but I don’t want it to repeat like that. I’ve tried adding the following to functions.php, but it’s hiding the sticky post everywhere now.

    add_action( 'pre_get_posts', function ( WP_Query $query ) {
    
        if ( ! $query->is_main_query() ) {
            return;
        }
    
        if ( ! $query->is_home() ) {
            return;
        }
    
        if ( $query->get( 'paged', 1 ) == 1 ) {
            return;
        }
    
        $query->set ( 'post__not_in', array( 658 ) );
    
    });
Viewing 3 replies - 1 through 3 (of 3 total)
  • Hello lisajwells,

    You have applied the three conditions in “pre_get_posts” filter but the code of ignoring the sticky post is out side the condition So please add it like this:

    if ( $query->get( 'paged', 1 ) == 1 ) {
           $query->set ( 'post__not_in', array( 658 ) );
            return;
        }

    Thanks

    Thread Starter lisajwells

    (@lisajwells)

    Thanks, Clarion.

    Unfortunately this doesn’t work either.
    I think the problem is in the ( $query->get( 'paged', 1 ) == 1 )

    The reason the post-ignoring code was outside of the conditional was that the three ifs before it had returns. The returns would cause the rest of the code to never run. So in pseudo-code, it would be:

    • If this is not the main query, forget all this and move on.
    • If this is not the home page (which includes the second posts page), forget all this and move on.
    • If this is the first paged page, forget all this and move on.
    • Still here? Don’t show that sticky post.

    To better understand the behavior, I’ve been playing with the date of the sticky post. With or without any of the functions above, if the publish date is such that it would appear on the first page, it appears at the top of the first page and does not appear on the second page, as expected. If the publish date would otherwise place it on the second page, it appears on both pages.

    I’m writing to the theme developer. Will keep you posted.

    Thread Starter lisajwells

    (@lisajwells)

    We have a winner, thanks to the Hello World theme developer:

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

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Sticky Post showing on all paged pages’ is closed to new replies.