How to hide private posts even if user is admin

admin2025-04-19  1

Even if admins, I dont want to view private posts for custom post type.

Added the following code.

function my_function( $query ) {
    if ( ! is_admin() && ( is_singular( 'my_post_type' ) || is_post_type_archive( 'my_post_type' ) ) ) {
        $query->set( 'post_status', 'publish' );
    }

    // The following is not related to this question
    if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
        $searchable_post_types = get_post_types( array( 'exclude_from_search' => false ) );
        if( in_array( 'my_post_type', $searchable_post_types ) ) {
            unset( $searchable_post_types['my_post_type'] );
            $query->set( 'post_type', $searchable_post_types );
        }
    }
}
add_filter( 'pre_get_posts', 'my_function' );

Is it wrong? Thanks.

Even if admins, I dont want to view private posts for custom post type.

Added the following code.

function my_function( $query ) {
    if ( ! is_admin() && ( is_singular( 'my_post_type' ) || is_post_type_archive( 'my_post_type' ) ) ) {
        $query->set( 'post_status', 'publish' );
    }

    // The following is not related to this question
    if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
        $searchable_post_types = get_post_types( array( 'exclude_from_search' => false ) );
        if( in_array( 'my_post_type', $searchable_post_types ) ) {
            unset( $searchable_post_types['my_post_type'] );
            $query->set( 'post_type', $searchable_post_types );
        }
    }
}
add_filter( 'pre_get_posts', 'my_function' );

Is it wrong? Thanks.

Share Improve this question asked Oct 30, 2019 at 9:54 pimstakpimstak 1
Add a comment  | 

1 Answer 1

Reset to default 0

I can't use is_singular( 'my_post_type' ) in pre_get_posts because the queried object is not set at this point. I can use instead the post_type query parameter.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745041654a281579.html

最新回复(0)