0

I'm using Gutenberg editor and I want to add a shortcode (using XYZ PHP Code) that uses the post id to retrieve certain ACF value.

I'm editing the home page where the last blog posts are shown, but I can't find a way to get the post_id of each item on the loop. I'm using this on the XYZ Shortcode:

<?php echo get_the_ID(); ?>

It always displays the same post_id, the one that belongs to the first post that gets displayed on the list.

How can I get the ID for each item on the loop?

enter image description here

I am missing something here?

4
  • If you're inside a custom loop, you might need to globalize the post object. Commented Aug 2, 2023 at 13:26
  • @ray-happyforms So... is there any way to do what I want?
    – Alvaro
    Commented Aug 2, 2023 at 15:28
  • @ray-happyforms not sure what you mean by "custom loop". This is the default loop created by TwentyTwentyThree theme when using Gutenberg editor.
    – Alvaro
    Commented Aug 2, 2023 at 16:20
  • @Alvaro, did my answer help, and more importantly, can you let us know how did you solve the issue? 🤔
    – Sally CJ
    Commented Aug 10, 2023 at 5:15

1 Answer 1

3

No, you did nothing wrong.

It's a known issue and in WordPress v6.1.3 and up to the current stable release as of writing (v6.2.2), it's happening because of the following lines in get_the_block_template_html() which returns the markup for the current (block-based) template:

$content = do_shortcode( $content );
$content = do_blocks( $content );

So as you could see, shortcodes in the post content (post_content) are being run before the blocks are parsed, which means that by the time your shortcode runs, the Query Loop block has not yet run, hence get_the_ID(), get_post()->ID, etc. would return the ID of the first post or whatever is the current post in the current loop.

In the past, it used to be that do_blocks() is being called before do_shortcode(), then in WordPress v6.1.2, the do_shortcode() call was removed and yet, added back in v6.1.3 (see changesets 55771 and 55830 in Trac), so I don't know if it will ever be back to any of that behaviors.

Nonetheless, there are 2 possible workarounds you can try:

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.