简体   繁体   English

试图在 HTML echo 语句中获取 WordPress PHP

[英]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.在阅读了许多 SO 文章后,我认为我有这个权利,但我不断收到错误消息。 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.基本上,在我的 content.php 页面模板中,我想根据您是在存档页面还是单个帖子页面上显示不同的文章标签。 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:但是这里发生的事情而不是它在页面上吐出 ID,所以生成的 HTML 看起来像这样:

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() (以及相当多的其他 WP 函数)有一个变体get_the_ID()你会想在这里使用。 the_ID() does its own echo internally; the_ID()在内部做自己的回声; get_the_ID() returns it. get_the_ID()返回它。

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.只需将您的代码修改为:默认情况下the_ID()具有 echo param true 以便它打印 id,但get_the_ID()返回与您的 html 代码连接的 ID。 You can get more details by clicking here .您可以通过单击此处获取更多详细信息。 And also removed the Double Qutoes from else part after the post_class() function.并且还在post_class()函数之后从 else 部分删除了 Double Qutoes。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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