I am creating a shortcode to fetch the categories of a given post and display them in a stylish way. I made the following shortcode:
function t3_categories_fonction(){ global $post; // Get the global post object // Get the post ID from the global post object if not provided //$post_id = $post->ID; $post_id = get_the_ID(); // test loop to display categories in a single string (stylization will come later) $post_cats = get_the_category($post_id); foreach($post_cats as $cat){ $result .= '-'; $result .= $cat->slug; } return $result; } add_shortcode('t3_categories', 't3_categories_fonction' );
However this shortcode always display the categories of the first post in the page, even when it is in a separate secondary loop, rather than the categories of the post in which the shortcode block is in (I am using block themes, I made the loops as blocks, my shortcode is inside the publication model block of my loop).
I tried both get_the_ID()
and the $post
global. The result is the same.
This problem is similar to that one I posted on StackOverflow and for which the solutions provided didn't fix the issue.