Conditional Tags for Custom Taxonomy in Custom Post Type

白昼怎懂夜的黑 提交于 2019-12-12 06:25:10

问题


I do hope you give me a practical answer for this (maybe simple problem for you). I have crated a Custom Post Type named (example:) "Cuspost" and I have Custom Taxonomy inside Cuspost named "Custax". Then I have taxonomies: "A Custax" and "B Custax" inside Custax.

What I want to do is just want to check the value of the Custax, for example with has_custax('a-custax') (similar to has_category('a-category'));

Next using is for this:

<?php if (has_custax('a-custax')) {
    echo 'do something A';
} else {
    echo 'do something B';
}

For your reference, I've read this (http://wordpress.org/support/topic/custom-taxonomies-conditional-tags#post-1110167) and it aint work.

Thanks for help.


回答1:


Solve with this function on functions.php similar to Justin Tadlock solutions

<?php function has_custax( $custax, $_post = null ) {
    if ( empty( $custax ) )
        return false;
    if ( $_post )
        $_post = get_post( $_post );
    else
        $_post =& $GLOBALS['post'];
    if ( !$_post )
        return false;
    $r = is_object_in_term( $_post->ID, 'custax', $custax );
    if ( is_wp_error( $r ) )
        return false;
    return $r;
}
?>

And this is the conditional tag. Can be used in/outside the loop:

<?php if ( has_custax( 'a-custax', $post->ID ) ) {
      echo 'do something A';
} else { echo 'do something B'; }; ?>

Credit to my friend Sulton Hasanudin



来源:https://stackoverflow.com/questions/11712389/conditional-tags-for-custom-taxonomy-in-custom-post-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!