2

I thought I had this right after reading many SO articles, but I keep getting errors. Basically, in my content.php page template, I wanted to display a different article tag based on whether you were on the archive or single post page. So I've been doing something like this:

<?php if ( is_archive() ) {
    echo '<article id="post-' . the_ID() . '">';
        } else {
    echo '<article id="post-' . the_ID() . ' . "post_class() . '">';
}
?>

But what happens here instead of it spits out the ID on the page so the resulting HTML looks like this:

1234<article id="post-">Content Goes Here</article>

when it should be....

<article id="post-1234">Content Goes Here</article>

so why isn't this showing up right?

1
  • I got it closer using code like this: echo '<article id="post-' . get_the_ID() . '"' . post_class() . '>'; So the class code appears but once again, outside of the archive tag. So it's a mess. Commented Dec 30, 2018 at 0:09

2 Answers 2

2

the_ID() (and quite a few other WP functions) has a variant get_the_ID() you'll want to use here. the_ID() does its own echo internally; get_the_ID() returns it.

Sign up to request clarification or add additional context in comments.

Comments

0

Just modfy your code to : the_ID() by default has echo param true so it print the id, but get_the_ID() return the ID which concatenate with your html code. You can get more details by clicking here. And also removed the Double Qutoes from else part after the post_class() function.

<?php if ( is_archive() ) {
    echo '<article id="post-' . get_the_ID() . '">';
        } else {
    echo '<article id="post-' . get_the_ID() . '". post_class() .'>';
}
?>

5 Comments

I see that but after adding that code, I received another error for code that was previously good. The error is: Parse error: syntax error, unexpected '<' in /www/webroot/mysite/wordpress/wp-content/themes/orchestra/template-parts/content.php on line 19 That code is: <?php the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); ?>
Also, If I swap those two echo statements, then that error appears on line 14, which is currently the first echo statement that doesn't have the post_class() at the end.
Yea, getting rid of . post_class() .' worked, but why?
<?php the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); ?> error for this line is dur to syntactical, and nothing to do with previous one.
post_class() was added in worng way. You should be very carfeull when you are using single quote and double quote in echo statement. Closing and Opening should be in a proper manner.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.