- This topic has 5 replies, 3 voices, and was last updated 2 years, 6 months ago by
Fernando.
-
AuthorPosts
-
September 28, 2022 at 10:14 am #2356666
Gary
Hi GP
Just looking for some guidance on how IDs behave inside a query loop block when using WordPress functions that rely on IDs in custom shortcodes.
I created a custom shortcode for displaying the parent category of a post e.g top level cat only not any children.
This shortcode works great in a GP elements content template but it doesn’t work in a query loop block for some reason.
I’ve tried changing the way I grab the post ID using get_the_ID() function which can be used in a loop but nothing seems to work like it does in the content template.
Therefore what is the best way to get and use IDs in a shortcode for use in a query loop block?
Thanks
September 28, 2022 at 3:24 pm #2356922Ying
StaffCustomer SupportHi Gary,
Can you share the code you used to create the shortcode?
Let me know!
September 28, 2022 at 4:01 pm #2356948Gary
Hi Ying
Sure, here’s the code that works in an Elements template when using the shortcode but doesn’t in a query loop block:
function gt_get_parent_terms($taxonomy = 'category') { global $post; $post_id = $post->ID; $catName = ""; foreach((get_the_category($post_id)) as $category){ if ($category->parent == 0) { $catName .= $category->name; } } return $catName; } add_shortcode('parent_cat', 'gt_get_parent_terms');
Note I tried changing the above
$post_id
variable to equal get_the_id() for use in the query loop but this doesn’t seem to work either, so I’m stumped as to why the ID part isn’t working when the shortcode is used within the query loop block?Thanks
September 28, 2022 at 5:58 pm #2357020Fernando Customer Support
Hi Gary,
This is a core WordPress thing. When you use get_the_ID() in a GenerateBlocks or WordPress Query Loop, the returned ID will always be the ID of the current page/post viewed, not the one in the current loop.
To address this, filter
render_block()
is used. You’ll need the add a Headline Block for instance and alter it via render_block() asget_the_ID()
would work with that method.Reference: https://developer.wordpress.org/reference/functions/render_block/
September 30, 2022 at 2:48 am #2358574Gary
Hi Fernando
Thanks for letting me know about how the ID is treated by WordPress, I had wondered if what I had was just grabbing the ID of the page rather than the query loop item.
You reminded me I have previously used the render_block function based on using a unique class attribute to alter the content of a block, so I’ll use that as starting point and hopefully I can get the top level category to show correctly.
Thanks
September 30, 2022 at 5:22 am #2358708Fernando Customer Support
Great! You’re welcome Gary! Just reach out anytime if you’ll need further assistance!
-
AuthorPosts
- You must be logged in to reply to this topic.