0

I have created a function to display my custom taxonomy ('market') terms. But the problem is that this outputs the first taxonomy term twice. Here is my function:

    function related_markets()
    {
        if ('news' === get_post_type()) {
            $terms = get_terms(array(
                'taxonomy' => 'market',
                'hide_empty' => false,
            ));
            foreach ($terms as $term) {
                $term_list .= '<a class="related-market btn btn-outline-secondary" href="' . esc_url(get_term_link($term)) . '">' . $term->name . '</a>';
                echo $term_list;
            }
        } elseif ('analysis' === get_post_type()) {
            $terms = get_terms(array(
                'taxonomy' => 'market',
                'hide_empty' => false,
            ));
            foreach ($terms as $term) {
                $term_list .= '<a class="related-market btn btn-outline-secondary" href="' . esc_url(get_term_link($term)) . '">' . $term->name . '</a>';
                echo $term_list;
            }
        }
    }
endif;

1 Answer 1

3

I think you want to show list of the category links right? but you are echo list inside the for-each loop. you have to write that outside of the loop.

foreach ($terms as $term) {
            $term_list .= '<a class="related-market btn btn-outline-secondary" href="' . esc_url(get_term_link($term)) . '">' . $term->name . '</a>';
        }
        echo $term_list;

Also don't forgot to initialize "$term_list" first in the function. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.