Search code examples
wordpressadvanced-custom-fieldscustom-taxonomy

Conditional ACF taxonomies & terms not working as expected (if has_term)


I've been racking my brains over this for ages and I can't find the solution I'm after.

In archive.php in Wordpress I want some conditional statements to say if this ACF taxonomy term is this then display something.

Putting the following code into the PHP file spits out the info I need...

<?php 
$terms = get_queried_object();
print_r($terms);
?>

...which reads as...

WP_Term Object ( [term_id] => 8 [name] => XANN’S VISION [slug] => xanns-vision [term_group] => 0 [term_taxonomy_id] => 8 [taxonomy] => themes [description] => [parent] => 0 [count] => 2 [filter] => raw )

But when I try to add some conditional logic, like this...

<?php if ( has_term("XANN'S VISION")) {
echo '<p>hello</p>';
} ?>

...I get nothing? Any help would be appreciated, thanks.

EDIT...with a little help I got it working for the slug name...

<?php
$terms = get_queried_object();
if ( $terms->slug === "xanns-vision") {
    echo '<p>hello</p>';
}
?>

Solution

  • Note the signature of has_term:

    has_term( string|int|array $term = '', string $taxonomy = '', int|WP_Post $post = null ): bool
    

    Further digging into the function's internals will show that when you don't specify the $post parameter, it will attempt to read from Wordpress global $post object instead.

    You haven't given us much context as to where you've placed your code, so I'm assuming that since you're retrieving the desired term through get_queried_object() that you're getting it through a term URL like /themes/xanns-vision.

    If you're simply looking for a condition to execute based on a specified term within that taxonomy, you can do a couple of things. You can either augment your condition to match against the ID (or name/slug) of the desired taxonomy like so:

    <?php
    $terms = get_queried_object();
    if ( $terms->name === "XANN'S VISION") {
        echo '<p>hello</p>';
    }
    ?>
    

    Otherwise, if you want something a little more resilient and render out a totally different layout based on your selected term query, you can add in a file to your theme named taxonomy-themes-xanns-vision.php:

    <?php
    echo '<p>hello</p>';
    ?>