1

I have a section in my website where i want to display just the private posts for logged in users, but the loop returns all posts (private and publish), is it possible to change this? I have the next code in my loop:

global $listingsearch, $listing_query, $wp_query;

$view = listingpress_get_listing_search_view();
$desktop_view = $view['d'];

And this

if ( $wp_query->have_posts() ) :

And this

while ( $wp_query->have_posts() ) :
                $wp_query->the_post();
2

You need to filter the main WordPress query using the pre_get_posts action. This code will get you started:

function show_only_private_post_for_logged_in_users( $query ) {

    if ( ! $query->is_main_query() || is_admin() ) {
        return;
    }

    if ( is_user_logged_in() ) {
        $query->set( 'post_status', 'private' );
    }
}
add_action( 'pre_get_posts', 'show_only_private_post_for_logged_in_users' );

It will only affect the main query and not on the WordPress admin side.

0

If you don't want to alter the main loop and you're looking for more of a widget/section I would throw something similar to the code below in functions.php:

function render_private_posts(){

    if ( is_user_logged_in() ) {

        $private_post_args = array(
            'post_type' => 'post',
            'post_status' => 'private',
            'posts_per_page'=> 5
        );

        $private_posts = new WP_Query( $private_post_args );

        $private_post_output = NULL;
        if ( $private_posts->have_posts() ) {
            $private_post_output = '<ul>';

            while ( $private_posts->have_posts() ) {
                $private_posts->the_post();
                $private_post_output .= '<li><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></li>';
            }

            $private_post_output .= '</ul>';
        }

        wp_reset_postdata();
        return $private_post_output;

    }

    return false;

}

You would then use echo render_private_posts(); where you want it.

0

what you can do is to get posts in a loop and get their ids, and pass it in another loop inside the first loop and simple just put this function

<?php
    if ( get_post_status ( $ID ) == 'private' ) {
    // do something here
    }
?>

and this will return posts with visibility status private. look at this link for better understanding https://codex.wordpress.org/Function_Reference/get_post_status

hope this helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.