質問

投稿がカスタム投稿タイプであるかどうかをテストする方法を探しています。たとえば、たとえば、私がこのようなコードを入れることができるサイドバーで:

 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帰属
所属していません wordpress.stackexchange
scroll top