Site logo

Archived topic

get_the_tag_list shows wrong tags when in sidebar

4 replies · Started by Claudia on August 10, 2022

Viewing posts 1–5 of 5

Hi,

we show the tags of a post in the sidebar with a shortcode [tags] hooked in generate_after_right_sidebar_content.
For the implementation we use a Hook Element.

function iw_taglist(){
        return '<div class="post-tag-list">' . get_the_tag_list() . '</div>';
}
add_shortcode('tags', 'iw_taglist');

So far so good, BUT the shortcode shows the wrong tags when implemented in the sidebar. When I put the same shortcode in the content the tags are correct (no matter if directly in the post, by a function or a Hook Element).

You can see it in this screenshot:
https://ibb.co/RQ9qpBR

Any idea why?

Regards
Claudia

Hi there,

the get_the_tag_list has 4 parameters see here:

https://developer.wordpress.org/reference/functions/get_the_tag_list/

The 4th one allows you specify an ID, which will be required when adding them in the sidebar as that is outside the WP loop. To get the ID dynamically we can use the: get_queried_object_id()

Try this updated snippet for your shortcode:

function iw_taglist(){
    if ( is_singular() ) :
    return get_the_tag_list(
        '<div class="post-tag-list"><ul"><li>',
        '</li><li>',
        '</li></ul></div>',
        get_queried_object_id()
    );
    endif;
}
add_shortcode('tags', 'iw_taglist');

Thanks a lot, that works!
And now that you wrote this, it's logical that it's cause there is no ID outside the loop...

solved

Glad to be of help!

This archived topic is closed to new replies.