-
-
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.
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
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