Conditional Tags for Custom Taxonomy in Custom Pos

2019-09-06 16:31发布

问题:

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