获取所有已注册的帖子类型插件的列表

时间:2011-11-21 作者:unfulvio

我想获得我注册的所有帖子类型的列表(数组)。

确切地说,我想找回他们的鼻涕虫。

有人能帮帮我吗?谢谢

4 个回复
最合适的回答,由SO网友:chrisguitarguy 整理而成

@EAMann的回答是正确的,但已经有一个内置的WordPress函数用于获取所有注册的帖子类型:get_post_types

<?php
// hook into init late, so everything is registered
// you can also use get_post_types where ever.  Any time after init is usually fine.
add_action( \'init\', \'wpse34410_init\', 0, 99 );
function wpse34410_init() 
{
    $types = get_post_types( [], \'objects\' );
    foreach ( $types as $type ) {
        if ( isset( $type->rewrite->slug ) ) {
            // you\'ll probably want to do something else.
            echo $type->rewrite->slug;
        }
    }
}

SO网友:EAMann

当你打电话的时候register_post_type(), 它将您的新帖子类型添加到一个名为$wp_post_types. 因此,您可以从中获得所有帖子类型的列表:

function get_registered_post_types() {
    global $wp_post_types;

    return array_keys( $wp_post_types );
}
The$wp_post_types 变量是包含CPT定义的数组,每组CPT参数(标签、功能等)映射到CPT的slug。使命感array_keys() 将为您提供一组CPT的Slug。

SO网友:Aamer Shahzad

最简单的方法是使用WordPress函数get\\u post\\u types();

<?php
$get_cpt_args = array(
    \'public\'   => true,
    \'_builtin\' => false
);
$post_types = get_post_types( $get_cpt_args, \'object\' ); // use \'names\' if you want to get only name of the post type.

// see the registered post types
echo \'<pre>\';
print_r($post_types);
echo \'</pre>\';

// do something with array
if ( $post_types ) {
    foreach ( $post_types as $cpt_key => $cpt_val ) {
       // do something.
    }
}
?>

SO网友:Pekz0r

更优雅的解决方案:

<?php
$cpt_args = [
    \'public\'   => true,
    \'_builtin\' => false
];

$type_slugs = array_map( function( $type ) {
    return $type->slug;
}, get_post_types( $cpt_args, \'objects\' ) );

结束

相关推荐

通过url传递评论id,并在url中附加评论帖子的slug

场景如下:我编写了一个自定义url规则,将注释id传递给模板,并将注释和注释元显示为单个页面(eg. http://example.com/reply/56) 而且效果很好。但现在我正试图完善这条规则,以便在URL中包含评论帖子slug。所以当我访问\'http://example.com/reply/56\' 它应该映射到\'http://example.com/the-post/reply/56\'. 我实际上被困在这一点上了。以下是我迄今为止所做的:有效的规则:<?php add_r