输出分类术语 - 如果选择 none,则显示 none

Output taxonomy terms - show none if none selected

我有一个有效的短代码,可以将分类法的术语输出为图像缩略图。

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

我目前的代码如下:

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;
}

我正在尝试使用针对 $termsif (!empty()) 变量来解决此问题,但我可能没有正确放置代码。

因此,如果未选择任何项,则不应输出任何内容。

我添加的代码如下:

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

  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
  )
  );

  if (!empty($terms)) {
    ob_start();
    echo '<div id="book-terms-wrap"><ul class="book-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;
  }
}

但不幸的是,这行不通,我做错了什么?

你的想法是正确的,但检查的地方不对。

wp_get_object_terms returns an empty array if the Post has no such terms.

get_terms、namely the WP_Term_query array of arguments passed in 接受您拥有的 includes 参数,但如果您不提供 includes,则默认 includes 是一个空数组。也就是说,传递一个空数组与根本不传递参数是相同的——这意味着,它完全忽略了 includes 限制,并且 returns 所有匹配任何其他限制的结果(在你的情况下,它只是 returns全部)。

所以简而言之,一旦调用 $post_terms 行,您就知道您没有条款。您可以使用以下内容:

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

// No terms found, skip the rest of the function
if ( empty($post_terms) )
  return false

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

顺便说一句,我有理由相信您也可以通过如下更改 wp_get_object_terms 行来完全跳过 get_terms 调用:

$terms = wp_get_object_terms($post->ID, $taxonomy, array('hide_empty' => false) );