I have the following code in PHP:
<?php if (function_exists("insert_audio_player")) {insert_audio_player("[audio:|titles=]"} ?>
Which renders an audio player to my page in WordPress. I need to call a custom field inside this code. My custom field code is also coded in PHP:
<?php print_custom_field('tc_filename'); ?>
Something like:
<?php if (function_exists("insert_audio_player")) {insert_audio_player("[audio:<?php print_custom_field('tc_filename'); ?>|titles=<?php print_c开发者_如何学Goustom_field('tc_title'); ?>]"} ?>
How can I use or integrate the second block of code with the first?
<?php
if (function_exists("insert_audio_player")) {
insert_audio_player("[audio:".print_custom_field('tc_filename')."|titles=".print_custom_field('tc_title')."]"
} ?>
You can make this easier to read using 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')
));
}
?>
Edit: based on your comment, the print_custom_field actually echo's the field, and doesn't return it, if there is no return function you can use, you need to use Output Buffering.
You can use a new function, which calls the print function but returns it instead of printing it to the screen:
function get_custom_field($field) {
ob_start();
print_custom_field($field);
return ob_get_clean();
}
And use
<?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')
));
}
?>
Edit: As stated by the OP, the print_custom_field()
function uses echo
rather than return
, so this answer will not work for this particular situation. See @Jacob's answer for a better solution.
Try this:
<?php
if (function_exists("insert_audio_player")) {
insert_audio_player(
"[audio:" . print_custom_field('tc_filename') .
"|titles=" . print_custom_field('tc_title') . "]"
);
}
?>
<?php if (function_exists("insert_audio_player")) {insert_audio_player("[audio:".function2()."|titles=".function3()."]"} ?>
then :
function function2()
{
print_custom_field('tc_filename');
}
function function3()
{
print_custom_field('tc_title');
}
精彩评论