samedi 28 décembre 2019

Output taxonomy terms - show none if none selected

I've got a working shortcode that outputs the terms of a taxonomy as image thumbnails.

It works great, BUT when none of the taxonomy terms are selected, it outputs ALL terms.

My current code is as follows:

add_shortcode( 'book-accreditation', 'book_accreditation_output' );
function book_accreditation_output($atts){

    ob_start();
    echo '<div id="book-terms-wrap"><ul class="book-terms">';

    global $post;
    $taxonomy = 'book_accreditation';
    $post_terms = wp_get_object_terms($post->ID, $taxonomy, array('fields' => 'ids'));

    $terms = get_terms( $taxonomy, array(
    'hide_empty' => false,
    'include'  => $post_terms
      )
  );

  foreach($terms as $term){
    $thumbnail = get_field('bkk_taxonomy_image', $term->taxonomy . '_' . $term->term_id);
    $thumbnail = $thumbnail['url'];
    $name = $term->name;
    $url = get_term_link($term, $taxonomy);
    echo '<li><img src="' . $thumbnail . '" class="accreditation-image"></li>';
  }
    echo '</ul></div>';
    $output = ob_get_clean();
    return $output;
}

I'm trying to fix this with if (!empty()) variable targeting the $terms, but i'm probably not putting the code correctly.

So if NO terms are selected, then nothing should output.

I'm adding the code as follows:

add_shortcode( 'book-accreditation', 'book_accreditation_output' );
function book_accreditation_output($atts){

  if (!empty($terms)) {
    ob_start();
    echo '<div id="book-terms-wrap"><ul class="book-terms">';

    global $post;
    $taxonomy = 'book_accreditation';
    $post_terms = wp_get_object_terms($post->ID, $taxonomy, array('fields' => 'ids'));

    $terms = get_terms( $taxonomy, array(
    'hide_empty' => false,
    'include'  => $post_terms
      )
  );

  foreach($terms as $term){
    $thumbnail = get_field('bkk_taxonomy_image', $term->taxonomy . '_' . $term->term_id);
    $thumbnail = $thumbnail['url'];
    $name = $term->name;
    $url = get_term_link($term, $taxonomy);
    echo '<li><img src="' . $thumbnail . '" class="accreditation-image"></li>';
  }
    echo '</ul></div>';
    $output = ob_get_clean();
    return $output;
  }
}

But this won't work unfortunately, what am I doing wrong here?

Aucun commentaire:

Enregistrer un commentaire