I want to hide posts without featured images from index pages, can someone please give me a function code for it or if there is a plugin that does this then please point me to it.
Thanks in Advance. M.C.
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.
Sign up to join this communityYou can manipulate the main WP_Query just before it asks the database for posts. Looking for an existing _thumbnail_id
meta field should suffice, so using the pre_get_posts
filter, something like this might work for you:
add_action("pre_get_posts", function($query) {
if(!is_front_page() || !$query->is_main_query()) {
return;
}
if(!array_key_exists("meta_query", $query->query_vars)) {
$query->query_vars["meta_query"] = array();
}
array_push($query->query_vars["meta_query"],
array(
'key' => '_thumbnail_id',
'compare' => 'EXISTS'
)
);
});
The conditional return at the start of the function is there to only target the main query on the front page, but leave alone any other queries (so it doesn't hide your posts without thumbnails from the archives, for example).