Site logo

Archived topic

Tag list in loop template

9 replies · Started by Jochen on February 13, 2023

Viewing posts 1–10 of 10

Hi, 
I'm using a block element / loop template to display a Custom Post Type Loop. Below the loop I want to display all available tags of the post type. When using the wp tags block, only the tag of the first loop element is displayed. How can I show all available tags automatically without putting them manually in a block?
Best Jochen

Hi there,

does the Tags Cloud block do what you need ?
If not let us know, and ill find a shortcode to do that.

Hi David,
yes, the tag cloud would work, but for now nothing is shown since it doesn't include cpt
thanks

the Tags, are those the default tags taxonomy used for regular posts ?

no, the tags are a separate custom post type taxonomy

OK, try adding this PHP Snippet to create a shortcode called: [cpt_tags]

function display_custom_taxonomy_terms() {
    $taxonomy = 'custom_taxonomy';
    $terms = get_terms([
        'taxonomy' => $taxonomy,
        'hide_empty' => false,
    ]);
 
    if (!empty($terms) && !is_wp_error($terms)) {
        echo '<ul>';
        foreach ($terms as $term) {
            echo '<li><a href="' . get_term_link($term) . '">' . $term->name . '</a></li>';
        }
        echo '</ul>';
    }
}
add_action('cpt_tags', 'display_custom_taxonomy_terms' );

On this line: $taxonomy = 'custom_taxonomy'; set the name of your taxonomy.

Hey, thank you. I changed the name of my taxonomy but unfortunately the shortcode is not executing, it only shows '[cpt_tags]' in the frontend.

I changed add_action to add_shortcode and it works, but now the tags are at the beginning of the page and not where I put them in the sidebar.

I figured it out, here is my working code:

function display_custom_taxonomy_terms() {
    $taxonomy = 'serie';
    $terms = get_terms([
        'taxonomy' => $taxonomy,
        'hide_empty' => false,
    ]);
 
    if (!empty($terms) && !is_wp_error($terms)) {
		$html = '<ul>';
        foreach ($terms as $term) {
            $html .= '<li><a href="' . get_term_link($term) . '">' . $term->name . '</a></li>';
        }
        $html .= '</ul>';
	return $html;
    }
}
add_shortcode('cpt_tags', 'display_custom_taxonomy_terms' );

Shortcodes are supposed to return your html, not echo it.
Thank you for your help

Apologies i copied my code from a function i used elsewhere and forgot to change it to return....

Glad to hear you got it resolved.

This archived topic is closed to new replies.