T
T
tbalero2015-10-02 22:32:42
WordPress
tbalero, 2015-10-02 22:32:42

How to display a field only when it is filled?

On a WordPress site, on the post page, to display category names without a link (custom taxonomy category 'genres'), the following code is used:

<?php

$array = array();
$cur_terms = get_the_terms( $post->ID, 'genres');
    foreach( $cur_terms as $cur_term ){
    $array[] = $cur_term->name;
    }
$comma_separated = implode(", ", $array);

echo '<div>Жанры:' . ' ' . $comma_separated . '</div>'; // term1, term2, term3

?>

(*at the output inside the div, the text looks like: Genres: Genre1, Genre2, Genre3 )
Question: How can I change this code to display the field on the site page only when it (the field) is filled? (that is, only when, when creating/editing a post, one or more categories from the custom taxonomy 'genres' are specified for this
post if) correctly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Vorotnev, 2015-10-03
@tbalero

$cur_terms = get_the_terms( $post->ID, 'genres' );

if( $cur_terms && ! is_wp_error( $cur_terms )  ) {

    $array = array();

    foreach( $cur_terms as $cur_term ) {
        $array[] = $cur_term->name;
    }

    $comma_separated = implode( ", ", $array );
    echo '<div>Жанры: ' . esc_attr( $comma_separated ) . '</div>'; // term1, term2, term3

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question