无法显示所有自定义分类标准值

时间:2019-10-20 21:26:35

标签: wordpress woocommerce custom-taxonomy

这是我的代码,用于显示所有分类法值。它有效,但仅显示第一个值,并且显示两次。如何停止重复此值?

//注册自定义分类法 函数commit_custom_taxonomy_Item(){

$labels = array(
    'name'                       => 'Poleca',
    'singular_name'              => 'Poleca',
    'menu_name'                  => 'Poleca',
    'all_items'                  => 'Wszyscy polecający',
    'parent_item'                => 'Parent Brand',
    'parent_item_colon'          => 'Parent Brand:',
    'new_item_name'              => 'Nowy Polecający',
    'add_new_item'               => 'Dodaj nowego polecającego',
    'edit_item'                  => 'Edytuj polecającą',
    'update_item'                => 'Update polecający',
    'separate_items_with_commas' => 'Oddziel przecinkami',
    'search_items'               => 'Szukaj recommend',
    'add_or_remove_items'        => 'Add or remove polecającego',
    'choose_from_most_used'      => 'Choose from the most used Brands',
);
$args = array(
    'labels'                     => $labels,
    'hierarchical'               => true,
    'public'                     => true,
    'show_ui'                    => true,
    'show_admin_column'          => true,
    'show_in_nav_menus'          => true,
    'show_tagcloud'              => true,
);
register_taxonomy( 'recommend', 'product', $args );

}

add_action( 'init', 'recommend_custom_taxonomy_item');


add_action( 'woocommerce_before_add_to_cart_button', 'add_recommend_term');
function add_recommend_term() {
    $terms = get_the_terms(get_the_ID(), 'recommend');
    $author_image = wp_get_attachment_image_src($img_id );
    foreach ( $terms as $term ) {
    if (!is_wp_error($terms) && !empty($terms)) { ?>
        <div class="recommend-name"><a href="<?php echo esc_url(get_term_link($terms[0])); ?>"><?php echo esc_html($terms[0]->name); ?> <br><?php echo esc_html($terms[0]->description);?></a></div>

    <?php }
}

1 个答案:

答案 0 :(得分:0)

只需用以下代码段替换上述代码的部分-

add_action( 'woocommerce_before_add_to_cart_button', 'add_recommend_term');
function add_recommend_term() {
    $terms = get_the_terms( get_the_ID(), 'recommend' );
    if ( $terms && ! is_wp_error( $terms ) ) : 
        foreach ( $terms as $term ) {
        ?>
        <div class="recommend-name">
            <a href="<?php echo esc_url( get_term_link( $term ) ); ?>">
                <?php echo esc_html( $term->name ); ?><br><?php echo esc_html( $term->description ); ?>
            </a>
        </div>
        <?php }
    endif;
}