【问题标题】:Insert PHP within function在函数中插入 PHP
【发布时间】:2015-04-05 10:36:00
【问题描述】:

我在 WordPress 中有一个子主题,我想在每篇文章的末尾插入此代码:

<?php the_tags(); ?>

我不想编辑 single.php。我想通过functions.php插入这段代码

我找到了这个帖子并在这个答案中使用了代码:https://wordpress.org/support/topic/insert-info-into-bottom-of-posts#post-3990037

它对我来说效果很好,但我不知道如何插入我的 PHP 代码。

这些是我尝试过但没有在前端反映我想要的东西:

$content.= '<?php the_tags(); ?>';

$content.= ' the_tags();';

$content.= <?php the_tags(); ?>;

$content.= the_tags();

如何更改该 WordPress 线程中的代码以包含 php?

谢谢。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    您试图将the_tags 的输出连接到$content,但the_tags 不返回任何内容。当您调用 the_tags 时,它会将输出发送到浏览器本身。

    the_tags 几乎只是get_the_tag_list 的包装器,它确实将内容作为字符串返回而不是输出。试试:

    $content .= get_the_tag_list();
    

    另外,只是为了澄清您的一些尝试到底出了什么问题:

    $content.= <?php the_tags(); ?>;
    

    &lt;?php 本质上意味着开始解释 PHP,此时我假设您已经打开了 PHP 标签,因此无需再次打开,尝试这样做会导致一个错误。

    $content.= ' the_tags();';
    

    这会将文字字符串the_tags(); 附加到$content 上。您不能将函数调用嵌入到这样的字符串中。

    $content.= '<?php the_tags(); ?>';
    

    最后一行只是我刚才提到的两个问题的组合。这将导致文字字符串&lt;?php the_tags(); ?&gt; 被附加到$content

    【讨论】:

    • 你好。感谢您解释我的代码错误的原因!我对学习 PHP 的工作原理非常感兴趣。我尝试输入 $content .= get_the_tag_list();它似乎没有奏效。我也试过 $content .= get_the_tags();那也没有用。有什么想法吗?
    • 天哪。当我意识到我在发布到 SE 之前已经注释掉了我的代码时,我开始这样做,因为我不希望任何东西反映在前端。您的代码有效!非常感谢。
    • 没问题!食蚁兽 > 香蕉蛞蝓 ;D
    • 呃,我不这么认为! :)
    猜你喜欢
    • 2015-07-22
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    相关资源
    最近更新 更多