How to get only posts, pages and custom post types in WordPress

I am trying to get Pages, Posts and Custom Post Types In WordPress website but it is showing some other things in the list.

My Code:

<?php $types = get_post_types( ['public'   => true ], 'objects' );
         foreach ( $types as $type ) {
    
            if ( isset( $type->labels->name) ) { ?>
           
           <?php echo $type->labels->name ?>
           <br>
           
           <?php }
} ?>

In this, I am getting:

Posts
Pages
Media
My Templates
Locations

But I only want Pages, Posts and Locations (Locations is the Custom Post Type).

Any help is much appreciated.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can make an array of the post types you don’t want and then check in_array() to see if they match before you output anything with them.

<?php
    //You'll want to get at the actual name for My Templates.
    //My attempt is just a guess.
    $types_array = array( 'attachment' , 'elementor_library' );
    $types = get_post_types( ['public'   => true ], 'objects' );
        foreach ( $types as $type ) {
            if( !in_array( $type->name, $types_array )) {
                if ( isset( $type->labels->name) ) {
                    echo $type->labels->name . '<br>';
                }     
            }
        }
?>

Method 2

I tried this and got the solution:

<?php
 $types = get_post_types( ['public'   => true ], 'objects' );
 $exclude = array( 'attachment' , 'elementor_library' );

    foreach ( $types as $type ) {
      if( !in_array( $type->name, $exclude )) {
            if ( isset( $type->labels->name) ) {
                echo $type->labels->name . '<br>';
            }     
        }
    }
?>

You are use this or the above one also.

In this, You will get:

Pages
Posts
Custom Post Types


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x