Last active
May 5, 2023 15:56
-
-
Save philhoyt/74691e9ce6cfaf35c078a8bf21631233 to your computer and use it in GitHub Desktop.
Remove posts with empty content from WordPress Search Results
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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