Skip to content

Instantly share code, notes, and snippets.

@timstl
Last active March 29, 2019 20:49
Show Gist options
  • Save timstl/93bce5a1af36d9d93ba828ec445bbb28 to your computer and use it in GitHub Desktop.
Save timstl/93bce5a1af36d9d93ba828ec445bbb28 to your computer and use it in GitHub Desktop.
Exclude featured posts from main WordPress blog loop
/**
* Exclude featured posts from main blog loop
*/
function bt_exclude_featured_from_blog_index( $query ) {
if ( ! is_admin() && $query->is_home() && $query->is_main_query() ) {
$post_ids = bt_featured_post_ids();
if ( ! empty( $post_ids ) ) {
$query->set( 'post__not_in', $post_ids );
}
}
}
add_action( 'pre_get_posts', 'bt_exclude_featured_from_blog_index' );
/*
* Query featured posts
* Includes the first 4 featured by default. Adjust $num for less or more.
* Uses an ACF True/False field with key "featured_post", which stores a true value as 1.
*/
function bt_featured_post_ids( $num = 4 ) {
$post_ids = array();
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'showposts' => $num,
'orderby' => 'date',
'order' => 'desc',
'meta_query' => array(
array(
'key' => 'featured_post',
'value' => 1,
'compare' => '=',
),
),
);
$c_query = new WP_Query( $args );
if ( $c_query->have_posts() ) {
while ( $c_query->have_posts() ) {
$c_query->the_post();
$post_ids[] = get_the_ID();
}
wp_reset_postdata();
}
return $post_ids;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment