简体   繁体   中英

Trying to get WordPress PHP inside of HTML echo statement

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?

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.

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() .'>';
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM