wp query – is_user_logged_in not working from WP-API (wp-json)

Question

I want to hide certain posts from visitors that are not logged in. The code below works perfectly when the visitor visit the page but not is I try to see all the pages from the API with wp-json/wp/v2/pages. Then the function is_user_logged_in always returns false even if the wordpress_logged_in_* cookie is applied. What am I missing here?

add_action( 'pre_get_posts', array( 'hide_post_when_not_reseller', 10, 1 );
public function hide_post_when_not_reseller( $query ) {
    $roles = array( 'administrator', 'reseller' );

    if ( is_user_logged_in() ) {
        $user = wp_get_current_user();
        foreach ( $roles as $role ) {
            if ( in_array( $role, $user->roles ) ) {
                $query->set(
                    'meta_query',
                    array(
                        'relation' => 'OR',
                        array(
                            'key'     => 'hide_post',
                            'value'   => '0',
                            'compare' => '=',
                        ),
                        array(
                            'key'     => 'hide_post',
                            'compare' => 'NOT EXISTS',
                        ),
                    )
                );
            }
        }
    }
}

0
Gibon Webb Uppsala 3 months 2021-07-15T07:51:49-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse