Skip to content

Instantly share code, notes, and snippets.

@mattyza
Created June 13, 2013 09:22
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 mattyza/7f3bc3a41c63b0cc1424 to your computer and use it in GitHub Desktop.
Save mattyza/7f3bc3a41c63b0cc1424 to your computer and use it in GitHub Desktop.
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