is_post_type_viewable()
云策文档标注
概述
is_post_type_viewable() 函数用于判断一个文章类型是否被视为“可查看”。对于内置文章类型(如 posts 和 pages),基于 'public' 属性评估;对于其他文章类型,则基于 'publicly_queryable' 属性评估。
关键要点
- 函数接受字符串或 WP_Post_Type 对象作为参数,返回布尔值表示文章类型是否可查看。
- 内置文章类型使用 'public' 属性,非内置文章类型使用 'publicly_queryable' 属性进行判断。
- 函数内部逻辑:$is_viewable = $post_type->publicly_queryable || ( $post_type->_builtin && $post_type->public )。
- 提供 'is_post_type_viewable' 过滤器,允许开发者自定义判断逻辑,但返回值必须为严格布尔类型以确保兼容性。
- 函数在 WordPress 4.4.0 引入,后续版本增加了参数类型支持和过滤器钩子。
代码示例
add_filter( 'is_post_type_viewable', function ( $is_viewable, $post_type ) {
if ( false == $is_viewable || 'sample_post_type' === $post_type->name ) {
return false;
}
return true;
}, 10, 2 );注意事项
过滤器返回值必须为布尔类型,非布尔值(即使是假值或真值)将导致函数返回 false,以避免 PHP 8.1+ 中的类型错误。
原文内容
Determines whether a post type is considered “viewable”.
Description
For built-in post types such as posts and pages, the ‘public’ value will be evaluated.
For all others, the ‘publicly_queryable’ value will be used.
Parameters
$post_typestring|WP_Post_Typerequired-
Post type name or object.
Source
function is_post_type_viewable( $post_type ) {
if ( is_scalar( $post_type ) ) {
$post_type = get_post_type_object( $post_type );
if ( ! $post_type ) {
return false;
}
}
if ( ! is_object( $post_type ) ) {
return false;
}
$is_viewable = $post_type->publicly_queryable || ( $post_type->_builtin && $post_type->public );
/**
* Filters whether a post type is considered "viewable".
*
* The returned filtered value must be a boolean type to ensure
* `is_post_type_viewable()` only returns a boolean. This strictness
* is by design to maintain backwards-compatibility and guard against
* potential type errors in PHP 8.1+. Non-boolean values (even falsey
* and truthy values) will result in the function returning false.
*
* @since 5.9.0
*
* @param bool $is_viewable Whether the post type is "viewable" (strict type).
* @param WP_Post_Type $post_type Post type object.
*/
return true === apply_filters( 'is_post_type_viewable', $is_viewable, $post_type );
}
Hooks
- apply_filters( ‘is_post_type_viewable’, bool $is_viewable, WP_Post_Type $post_type )
-
Filters whether a post type is considered “viewable”.
Skip to note 2 content
Munaf Vichhi
Using this hook you can hide single custom posts URL.
add_filter( 'is_post_type_viewable', function ( $is_viewable, $post_type ) { if ( false == $is_viewable || 'sample_post_type' === $post_type->name ) { return false; } return true; }, 10, 2 );