ACF Field, hide taxonomy title and image when no nothing selected in post

admin2025-06-06  7

I have added a custom taxonomy image through ACF.

My code is as follows.

<?php 
    global $post;
    $tax = 'directory_features';
    $terms = get_the_terms($post,$tax);

  foreach( $terms as $term ) {

        $term_link = get_term_link( $term );
        $image = get_field('svcta_favorites_image',$term);

        if( $term->count > 0 ) {
            echo '<li>';
            echo '<img src="' . $image['url'] . '" alt="' . $image['alt'] .'"><br>';       
            echo '</li>';

        } elseif( $term->count !== 0 ) {
            echo '' . $term->name .'';
        }
    }
?>

If a post does not have an items in the taxonoimy selected, I get the following error.

Warning
Invalid argument supplied for foreach() in /home/webspera/public_html/SVCTA/wp-content/themes/pro-child/taxonomy_directory_category-weddings.php
on line 
168

How can I have this just hide the field if nothing has been selected?

I am not a porgrammer so thanks in advance for the help.

I have added a custom taxonomy image through ACF.

My code is as follows.

<?php 
    global $post;
    $tax = 'directory_features';
    $terms = get_the_terms($post,$tax);

  foreach( $terms as $term ) {

        $term_link = get_term_link( $term );
        $image = get_field('svcta_favorites_image',$term);

        if( $term->count > 0 ) {
            echo '<li>';
            echo '<img src="' . $image['url'] . '" alt="' . $image['alt'] .'"><br>';       
            echo '</li>';

        } elseif( $term->count !== 0 ) {
            echo '' . $term->name .'';
        }
    }
?>

If a post does not have an items in the taxonoimy selected, I get the following error.

Warning
Invalid argument supplied for foreach() in /home/webspera/public_html/SVCTA/wp-content/themes/pro-child/taxonomy_directory_category-weddings.php
on line 
168

How can I have this just hide the field if nothing has been selected?

I am not a porgrammer so thanks in advance for the help.

Share Improve this question asked Nov 20, 2018 at 6:28 Micah KMicah K 155 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Seems the your post doesn't attach any taxonomy. So just try to replace your code with this:

<?php 
global $post;
$tax = 'directory_features';
$terms = get_the_terms($post,$tax);
if ( $terms && ! is_wp_error( $terms ) ){
    foreach( $terms as $term ) {
        $term_link = get_term_link( $term );
        $image = get_field('svcta_favorites_image',$term);
        if( $term->count > 0 ) {
            echo '<li>';
            echo '<img src="' . $image['url'] . '" alt="' . $image['alt'] .'"><br>';       
            echo '</li>';

        } elseif( $term->count !== 0 ) {
            echo '' . $term->name .'';
        }
    }
}
?>
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749167654a316932.html

最新回复(0)