How to exclude empty pages from WordPress Search Results

Pages with no content can appear in search results. To address this issue, I used the ‘pre_get_posts’ function to exclude any ‘post’ with an empty ‘post_content’ field from the search query.

Here’s the code I used:

* Exclude posts with empty post_content from search results
function modify_search_query( $query ) {
// Check if this is a search query and not an admin query
if ( $query->is_search() && ! is_admin() ) {
// Add a filter to exclude posts with empty post_content
add_filter( 'posts_where', 'exclude_empty_post_content' );
// Remove the filter after the search query has been modified
add_action( 'wp', function() {
remove_filter( 'posts_where', 'exclude_empty_post_content' );
} );
function exclude_empty_post_content( $where ) {
global $wpdb;
// Add a condition to exclude posts with empty post_content
$where .= " AND ({$wpdb->prefix}posts.post_content != '')";
return $where;
add_action( 'pre_get_posts', 'modify_search_query' );





Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.