如何在PHP中返回使用"foreach"创建的函数作为字符串的所有内容,以使用wordpress发送联系人表单7动态字段



我想用contactform 7动态隐藏字段wordpress插件发送一封电子邮件,以获取电子邮件的动态内容。这在使用短代码时是可能的。所以我写了快捷代码和函数,看起来它可以工作,因为在网站上,会显示正确的输出,但它不会随邮件一起发送。我需要通过显示为列表的ID从几个帖子和自定义字段中获取内容。

当存在简单的return 'random text';时,它发送正确的内容但是它不发送任何带有echo的内容。

那么,我如何才能以某种方式获得函数创建的内容,即它是一个简单的return,可以发送?

function show_list_function() {
if(!empty($_SESSION['acts'])){
foreach($_SESSION['acts'] as $actID){ //this gives the right content, but doesn't send with the mail
echo get_the_title($actID); 
the_field('lange', $actID); 
}    
} else {
return 'Nothing selected'; //this is working
}
}
add_shortcode( 'show_list', 'show_list_function' );

感谢您的帮助和提示!

短代码输出不能回显,必须返回,因为do_shortcodeecho do_shortcode()使用

来自编码:

请注意,由shortcode调用的函数永远不应该产生任何类型的输出。短代码函数应返回用于替换短代码的文本。直接产生输出将导致意想不到的结果。

function show_list_function() {
// Init $output as something 
$output = '';
if(!empty($_SESSION['acts'])){
foreach($_SESSION['acts'] as $actID){ //this gives the right content, but doesn't send with the mail
// concatenate the $output string
$output .= get_the_title($actID); 
$output .= get_field('lange', $actID); 
}    
} else {
$output = 'Nothing selected'; //this is working
}
return $output;
}
add_shortcode( 'show_list', 'show_list_function' );

您可以使用ob_start((和ob_get_clen((;

function show_list_function() {
ob_start();
if(!empty($_SESSION['acts'])){
foreach($_SESSION['acts'] as $actID){ //this gives the right content, but doesn't send with the mail
echo get_the_title($actID); 
the_field('lange', $actID); 
}    
} else {
echo 'Nothing selected'; //this is working
}
$html = ob_get_clean();
return $html;
}
add_shortcode( 'show_list', 'show_list_function' );

最新更新