Add Snippet To Project
Are you wondering how to display private posts on your WordPress website only to logged-in users? By default, private posts in WordPress are only visible to administrators and editors. However, there are times when you may want to grant access to private content for registered users. In this article, we will show you how to easily display private posts to logged-in users, allowing you to create a more personalized and exclusive experience for your site visitors.
function wpturbo_display_private_posts( $query ) {
if( is_user_logged_in() ) {
$query->set( 'post_status', array( 'publish', 'private' ) );
}
}
add_action( 'pre_get_posts', 'wpturbo_display_private_posts' );
The code snippet provided is used to display private posts to logged-in users on a WordPress website.
The first part of the code defines a function called wpturbo_display_private_posts()
. This function takes the $query
parameter, which represents the current query being executed.
Inside the function, there is a conditional statement that checks if the user is logged in using the is_user_logged_in()
function. This function returns true if the user is logged in and false otherwise.
If the user is logged in, the code sets the post_status
parameter of the query to an array containing both 'publish'
and 'private'
. By default, WordPress only retrieves published posts, so by including the 'private'
status, it ensures that private posts are included in the query results.
Finally, the wpturbo_display_private_posts()
function is hooked into the pre_get_posts
action using the add_action()
function. This action fires before the main query is executed, allowing us to modify the query to include private posts for logged-in users.
By adding this code to your WordPress website, private posts will be visible to logged-in users when they visit the frontend or backend of your site.