如何在WordPress中仅获取帖子、页面和自定义帖子类型

时间:2021-01-08 作者:Rahul Kumar

我试图在WordPress网站上获取页面、帖子和自定义帖子类型,但它显示了列表中的其他内容。

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 }
} ?>
在这方面,我得到了:

Posts
Pages
Media
My Templates
Locations
但我只想要页面、帖子和位置(位置是自定义帖子类型)。

非常感谢您的帮助。

2 个回复
最合适的回答,由SO网友:Tony Djukic 整理而成

您可以创建一个不需要的帖子类型数组,然后检查in_array() 在输出任何内容之前,先查看它们是否匹配。

<?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>\';
                }     
            }
        }
?>

SO网友:Rahul Kumar

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>\';
            }     
        }
    }
?>
您也可以使用此选项或以上选项。

In this, You will get:

Pages
Posts
Custom Post Types