1

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.

2
  • Is this shortcode in a basic page? Have you tried testing the shortcode in a very simple page, using either the classic editor or just a standalone Custom HTML or shortcode block (not inside the publication nodel block)?CommentedJan 28 at 23:28
  • @JeffCohan This shortcode is on the front page template and the search results template. I use a similar shortcode on my post template (outside any queries) to get the post's modified date and it works fine but this isn't surprising because a post page is only one post anyways.CommentedJan 30 at 10:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.