我正在寻找一种测试帖子是否是自定义帖子类型的方法。例如,在说我可以使用这样的代码的侧边栏中:

 if ( is_single() ) {
     // Code here
 }

我只想为自定义帖子类型进行代码测试。

有帮助吗?

解决方案

给你: get_post_type() 接着 if ( 'book' == get_post_type() ) ... 按照 条件标签>帖子类型 在法典中。

其他提示

if ( is_singular( 'book' ) ) {
    // conditional content/code
}

以上是 true 查看自定义帖子类型的帖子时: book.

if ( is_singular( array( 'newspaper', 'book' ) ) ) {
    //  conditional content/code
}

以上是 true 查看自定义帖子类型的帖子时: newspaper 或者 book.

这些和更多条件标签 可以在这里查看.

将其添加到您的 functions.php, ,并且您可以具有循环内部或外部的功能:

function is_post_type($type){
    global $wp_query;
    if($type == get_post_type($wp_query->post->ID)) 
        return true;
    return false;
}

因此,您现在可以使用以下内容:

if (is_single() && is_post_type('post_type')){
    // Work magic
}

测试帖子是否是 任何 自定义帖子类型,获取所有不内置帖子类型的列表,并测试该帖子的类型是否在该列表中。

作为一个函数:

/**
 * Check if a post is a custom post type.
 * @param  mixed $post Post object or ID
 * @return boolean
 */
function is_custom_post_type( $post = NULL )
{
    $all_custom_post_types = get_post_types( array ( '_builtin' => FALSE ) );

    // there are no custom post types
    if ( empty ( $all_custom_post_types ) )
        return FALSE;

    $custom_types      = array_keys( $all_custom_post_types );
    $current_post_type = get_post_type( $post );

    // could not detect current type
    if ( ! $current_post_type )
        return FALSE;

    return in_array( $current_post_type, $custom_types );
}

用法:

if ( is_custom_post_type() )
    print 'This is a custom post type!';

如果出于任何原因您已经可以访问全局变量$ post,则可以简单地使用

if ($post->post_type == "your desired post type") {
}

如果您想对所有自定义帖子类型进行通配符检查:

if( ! is_singular( array('page', 'attachment', 'post') ) ){
    // echo 'Imma custom post type!';
}

这样,您就不需要知道自定义帖子的名称。此外,即使您以后更改自定义帖子的名称,代码仍然可以正常工作。

许可以下: CC-BY-SA归因
scroll top