Archived topic
How to include PHP within Query Loop on homepage
8 replies · Started by Ted on February 21, 2023
I've got 2 different Query Loops on the homepage, and they work just fine, however ...
I'm wanting to add some custom meta info after the title, Disqus comment counts, but the PHP I'm using doesn't seem to represent posts within the loop, but the homepage. I'm including this within the loop, for example:
<?php echo get_the_ID(); ?>
... and instead of showing the ID for the particular post, it's showing the ID for the homepage page.
I'm using Ad Inserter Pro to target a P tag with the class "homepage-disqus-comment-count" and then have the P tag inserted using a Heading block.
Do you have any suggestions how I can get <?php echo get_the_ID(); ?> within a Query Loop to show the ID for the post, rather than the homepage?
To assist, I've created the following shortcode:
function display_post_id() {
$id = get_the_ID();
$id = "<p>Post ID:".$id."</p>";
return $id;
}
add_shortcode('post_id', 'display_post_id' );
... and am inserting that within the top Query Loop. It's not showing the post ID, though, but the ID for the homepage.
This is what the Editor looks like for the homepage:

And this is what it looks like:

Hi Ted,
That won't work on Query loops.
You'll need to create a Headline Block, and replace the text of that Headline Block through a Filter.
For instance, add a Headline Block with text "placeholder". Give it a class of replace-gb-headline-text.
Adding Custom Classes: https://wordpress.com/support/wordpress-editor/adding-additional-css-classes-to-blocks/
Then add this snippet:
add_filter( 'render_block', function( $block_content, $block ) {
if ( !is_admin() && ! empty( $block['attrs']['className'] ) && strpos( $block['attrs']['className'], 'replace-gb-headline-text' ) !== false ) {
$myreplace = 'placeholder';
$myinsert = 'Post ID: ' . get_the_ID();
$block_content = str_replace( $myreplace, $myinsert , $block_content );
}
return $block_content;
}, 10, 2 );
Adding PHP: https://docs.generatepress.com/article/adding-php/#code-snippets
The posts' IDs are now showing up! Thanks, Fernando. I'll work on getting the rest of the code in place now.
You're welcome, Ted!
Hot dog! It worked!! Thanks so much, Fernando.
Glad that worked! You're welcome, Ted!