WordPress Snippets at WPcustoms

Exclude sticky posts from main query

Sticky posts are intended to be on top. This function excludes them from the main query so you can add them with a new WP_Query above the main loop. Use this snippet to modify the query with pre_get_posts and forward our query arguments ignore_sticky_posts and post__not_in


/**
 * Snippet Name: Exclude sticky posts from main query
 * Snippet URL: https://wpcustoms.net/snippets/exclude-sticky-posts-from-main-query/
 */
  function wpc_exclude_sticky_posts( $query ) {

if ( $query->is_home() && $query->is_main_query() )
$query->set( 'ignore_sticky_posts', 1 );
$query->set( 'post__not_in', get_option( 'sticky_posts' ) );
}
add_action( 'pre_get_posts', 'wpc_exclude_sticky_posts' );