Skip to content

Instantly share code, notes, and snippets.

@philhoyt
Last active May 5, 2023 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philhoyt/74691e9ce6cfaf35c078a8bf21631233 to your computer and use it in GitHub Desktop.
Save philhoyt/74691e9ce6cfaf35c078a8bf21631233 to your computer and use it in GitHub Desktop.
Remove posts with empty content from WordPress Search Results
<?php
/**
* 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' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment