Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Hide protected posts from the default homepage and all archive screens, in the main query, in WordPress.
add_filter( 'pre_get_posts', 'mattyza_custom_maybe_load_post_hider' );
// Conditionally apply a filter to hide protected posts. The condition is that it must be the main query and either an archive or the default homepage.
// If the conditions aren't met, be sure to remove the filter, in case it is inadvertantly applied.
function mattyza_custom_maybe_load_post_hider ( $q ) {
if ( $q->is_main_query() && ( $q->is_archive() || $q->is_home() ) ) {
add_filter( 'posts_where', 'mattyza_custom_hide_protected_posts' );
} else {
remove_filter( 'posts_where', 'mattyza_custom_hide_protected_posts' );
}
return $q;
} // End mattyza_custom_maybe_load_post_hider()
// Small utility function to modify database queries to hide protected posts.
function mattyza_custom_hide_protected_posts( $where ) {
global $wpdb;
return $where .= " AND {$wpdb->posts}.post_password = '' ";
} // End mattyza_custom_hide_protected_posts()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment