• Wanted sticky posts to show on category pages rather than the home page so put the following code in functions php which worked fine but of course they now all appear on the home page which I don’t want. Only want stickies to appear on the category pages but cant work out how to stop stickes showing on home page. Maybe having a bit of a mental block, could well be as I have had to repost this message as I put the wrong title in the Topic Title last time and couldn’t change it. Not having a good day.

    Code I have used in function.php to show stickies on category pages:

    
    add_filter('pre_get_posts', 'exclude_category');
    function get_term_sticky_posts()
    { if ( !is_category() ) return false;
    $stickies = get_option( 'sticky_posts' );
    if ( !$stickies ) return false;
    $current_object = get_queried_object_id();
    $args = ['nopaging' => true,
    'post__in' => $stickies,
    'cat' => $current_object,
    'ignore_sticky_posts' => 1,
    'fields' => 'ids' ];
    $q = get_posts( $args );
    return $q;}
    add_action( 'pre_get_posts', function ( $q )
    {if (    !is_admin() && $q->is_main_query() && $q->is_category() ) 
    {if ( function_exists( 'get_term_sticky_posts' ) ) {$stickies = get_term_sticky_posts();
                if ( $stickies ) {$q->set( 'post__not_in', $stickies )
    if ( !$q->is_paged() ) {add_filter( 'the_posts', function ( $posts ) use ( $stickies )
    {$term_stickies = get_posts( ['post__in' => $stickies, 'nopaging' => true] );
    $posts = array_merge( $term_stickies, $posts );
    return $posts; }, 10, 1 ); } } } } }); 
    

    Any help much appreciated.

    • This topic was modified 7 years, 9 months ago by Jan Dembowski.
Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    You have to stop the default query from doing stickies on your home page, as that is the default behavior regardless of what you do with category queries. You’ll need another section of your callback (or add another callback) for “the_posts” that, when $q->is_home() is true, pull the sticky posts off the top of the passed posts array and place them back in reverse chronological order. I believe you’ll need a custom usort() callback to properly order the posts.

Viewing 1 replies (of 1 total)

The topic ‘Changed Sticky Posts to show in Category – How to prevent showing on Home page’ is closed to new replies.