【问题标题】:Using PHP code in PHP code?在 PHP 代码中使用 PHP 代码?
【发布时间】:2011-07-15 10:23:15
【问题描述】:

我在 PHP 中有以下代码:

<?php if (function_exists("insert_audio_player")) {insert_audio_player("[audio:|titles=]"} ?>

在 WordPress 中将音频播放器呈现到我的页面。我需要在这段代码中调用一个自定义字段。我的自定义字段代码也是用 PHP 编码的:

<?php print_custom_field('tc_filename'); ?>

类似:

<?php if (function_exists("insert_audio_player")) {insert_audio_player("[audio:<?php print_custom_field('tc_filename'); ?>|titles=<?php print_custom_field('tc_title'); ?>]"} ?>

如何使用第二个代码块或将第二个代码块与第一个代码块集成?

【问题讨论】:

  • @Jacob @jnpcl 感谢您的帮助 - 现在它按我需要的方式工作了!谢谢!

标签: php wordpress templating


【解决方案1】:
<?php 
if (function_exists("insert_audio_player")) {
    insert_audio_player("[audio:".print_custom_field('tc_filename')."|titles=".print_custom_field('tc_title')."]"
} ?>

您可以使用sprintf() 使其更易于阅读

<?php 
if (function_exists("insert_audio_player")) {
    insert_audio_player(sprintf(
        '[audio:%s|titles=%s]', 
        print_custom_field('tc_filename'), 
        print_custom_field('tc_title')
    ));
} 
?>    

编辑:根据您的评论,print_custom_field实际上是echo的字段,并没有返回它,如果没有可以使用的返回函数,则需要使用Output Buffering

你可以使用一个新函数,它调用 print 函数但返回它而不是打印到屏幕上:

function get_custom_field($field) {
    ob_start();
    print_custom_field($field);
    return ob_get_clean();
}

并使用

<?php 
if (function_exists("insert_audio_player")) {
    insert_audio_player(sprintf(
        '[audio:%s|titles=%s]', 
        get_custom_field('tc_filename'), 
        get_custom_field('tc_title')
    ));
} 
?> 

【讨论】:

  • 我相信你错过了一个结束)
  • @Jacob:我相信我也错过了一个。你原来少了两个。 :)
  • @Jacob @jnpcl @AbiusX 感谢您的回答。也许这是 wordpress 或音频播放器插件的一个功能,但后来我添加了你的任何代码,我在 [audio:] 标记之前有 tc_filename var =\ 我不明白为什么。比如:test.mp3[audio:]
  • @alekseygr 我已经更新了使用输出缓冲的答案,您使用的打印功能是回显数据而不是返回它。
  • @Jacob 感谢您的回答,但后来我使用您的代码我在第二部分代码的末尾有PHP Parse error: syntax error, unexpected '}
【解决方案2】:

编辑:正如 OP 所述,print_custom_field() 函数使用echo 而不是return,因此此答案不适用于这种特殊情况。请参阅@Jacob 的答案以获得更好的解决方案。

试试这个:

<?php
    if (function_exists("insert_audio_player")) {
        insert_audio_player(
            "[audio:" . print_custom_field('tc_filename') .
            "|titles=" . print_custom_field('tc_title') . "]"
        );
    }
?>

【讨论】:

  • 感谢您的帮助。现在尝试实现@Jacob 的答案)
【解决方案3】:
<?php if (function_exists("insert_audio_player")) {insert_audio_player("[audio:".function2()."|titles=".function3()."]"} ?>

然后:

function function2()
{
print_custom_field('tc_filename');
}
function function3()
{
print_custom_field('tc_title');
}

【讨论】:

  • 您可以通过这种方式添加 if 和其他逻辑。
  • 也许你应该提到这一点,而不是使用像 function2 和 function3 这样的名称。
  • 或许可以,但请看问题。
  • @AbiusX 你能参考问题的哪一部分?
  • 我的意思是这个问题太简单了,太简单地将函数连接到字符串!所以我定义了新的函数让被问者更好地理解。
猜你喜欢
  • 1970-01-01
  • 2014-06-03
  • 2013-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多