仅根据支持获取帖子类型


9

我正在尝试检索包含内置和自定义帖子类型的列表:

$post_types = get_post_types(array(
  'public' => TRUE,
), 'objects');

以上差不多的工作,但我想排除attachment从这个名单,只有回归后的类型与特定的支持,如editortitlethumbnail。这可能吗?

Answers:


9

我发现这get_post_types_by_support()似乎是获得所需结果的解决方案:

$post_types = get_post_types_by_support(array('title', 'editor', 'thumbnail'));

以上将返回postpage以及任何自定义后类型的支持titleeditorthumbnail

由于这也会返回私人帖子类型,因此我们可以遍历列表并检查该类型在前端是否可见。这可以通过使用以下is_post_type_viewable()功能来完成:

foreach ($post_types as $key => $post_type) {
  if (!is_post_type_viewable($post_type)) {
    unset($post_types[$post_type]);
  }
}

请注意:这在大多数 情况下都适用。
cybmeta

4

get_post_types()接受参数数组来匹配post类型对象的字段。因此,您可以执行以下操作(未经测试):

$post_types = get_post_types(array(
  'public'   => true,
  'supports' => array( 'editor', 'title', 'thumbnail' )
), 'objects');

不幸的是,您不能在此函数中设置诸如“ exclude”之类的东西,而且您只能获得完全 支持的帖子类型,'editor', 'title', 'thumbnail'更多也不少。

或者,您可以使用get_post_types_by_support()(仅适用于WP 4.5及更高版本。此外,请注意,您也不能使用此功能排除特定的帖子类型,但是对于支持的特定情况,大多数情况下editor, title, thumbnail将排除附件的帖子类型)。

$post_types = get_post_types_by_support( array( 'editor', 'title', 'thumbnail' ) );

如果您希望在任何情况下都可以使用,我会尝试根据更广泛的条件获取帖子类型,然后构建自己的数组,如下所示:

$_post_types = get_post_types_by_support( array( 'editor', 'title', 'thumbnail' ) );

$post_types = [];

foreach($_post_types as $post_type) {
    // In most cases, attachment post type won't be here, but it can be
    if( $post_type->name !== 'attachment' ) {
        $post_types[] = $post_type;
    }
}

使用supports似乎不起作用?我有一个支持的自定义帖子类型,editor如果使用它,supports => array('editor')我会得到空的结果吗?您的第二种方法似乎可行。
Cyclonecode

2
看来我们可以使用get_post_types_by_support()支持来实现这一目标。
Cyclonecode

0

OP问题最简单的方法是从返回的数组中取消设置“ attachment”。

$post_types = get_post_types(array('public' => TRUE,), 'objects');
unset($post_types['attachment']);

尽管不如其他解决方案那么优雅,但开销却最小。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.