• Resolved sventertain

    (@sventertain)


    Hello,

    just wondering why my little php snippet only works once.

    Added this small script inside a Gutenberg post loop area to add an ACF variable to css.

    <?php while (have_posts()) : the_post(); ?>
       <style type="text/css">
       li.post-<?php echo esc_attr( get_the_ID() ); ?> {    
           some css here
       }
       </style> 
    <?php endwhile; ?>

    Adding the script as a shortcode inside the post loop element works fine on archive template with twenty twenty four.

    But if i try to add the script shortcode inside another post loop element on a page, it doesn’t show up and no <style> is added. Seems it code only works once…

    I’ve already tried to use it as a universal snippet with an ending ‘?>’
    No condition logics.

    Can you help? Many thanks in advance!

    Best, Sven

Viewing 4 replies - 1 through 4 (of 4 total)
  • Plugin Author Mircea Sandu

    (@gripgrip)

    Hi @sventertain,

    If you are adding the shortcode inside a loop you should not have to run the while loop there – have you tried adding it without the while loop? Just the style tag part?

    Thread Starter sventertain

    (@sventertain)

    Hi, i think i need the while loop to set different background colors to each post teaser and get the id as unique identifier with it…

    Just tried without the while loop and only the first post teaser color is set. Still works only once on the archive template and nowhere else.

    Any ideas?

    Plugin Author Mircea Sandu

    (@gripgrip)

    Hi Sven,

    I can see the issue, the loop should not be needed in the Loop block as that shortcode will get executed for each post already, but the global variables like get_the_ID() will return the same ID (the first post id) each time.

    If you create a simple snippet with the following code and use it as a shortcode you will see the id does not change:

    echo get_the_ID();

    This seems to be a limitation of how the query loop block works: https://github.com/WordPress/gutenberg/issues/43053

    Thread Starter sventertain

    (@sventertain)

    Hey Mircea,

    thank you for getting into it!
    I took a quick a look on the Meta Field Block Plugin. Using your shortcode as dynamic content did the trick without the while loop.

    That made my day!

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘PHP snippet shortcode only works once’ is closed to new replies.