我希望你们今天过得愉快。我正在开发一个带有自定义的短代码和其他东西的视频播放器插件,但是我的短代码呈现有问题。目前,我的短代码内容是用echo呈现的,这很好,但是它不能在页面内容中呈现,所以我不得不以某种方式将它更改为返回方法,但是它有foreach循环,如果它中有其他语句,所以我不能只执行return ' '.foreach($x as $s){}.' ';之类的操作,那么你们知道如何解决这个问题吗?我还尝试将所有内容都放在函数中,并试图在函数中呈现它,比如:return ' '.renderdata().' ';,它可以工作,但是它在内容中不呈现。
这是我的短代码函数
function myshortcode( $atts = array() ) {
$data = ['some array with video data'];
foreach($data as $d){
echo "$d";
}
}
add_shortcode('someshortcode', 'myshortcode'); 任何帮助都是非常感谢的,谢谢。
EDIT:由于PHP .,我能够处理问题
解决方案:
function myshortcode() {
ob_start();
// HTML here
return ob_get_clean();
}发布于 2021-04-27 19:10:54
很高兴听说你已经解决了这个问题。下面是一些例子,说明如何从一个短代码中返回html。
正如您已经发现的,您可以使用ob_start()和ob_get_clean()来缓冲html。在其中,您可以回显标记或退出PHP,并编写普通HTML。
function my_shortcode() {
ob_start();
echo 'some HTML here';
?>
Or outside of the PHP tags如果短代码位于主题内,则还可以在输出缓冲区中使用get_template_part()。通过这种方式,您可以使短代码回调看起来更干净一些,因为HTML将在一个单独的文件中找到它的主页。如果需要,还可以将数据传递给模板部件。
function my_shortcode() {
$template_part_args = array(
'key' => 'value',
);
ob_start();
get_template_part(
'path/to/template/part',
'optional-name', // use null, if not named
$template_part_args // access with $args in the template part file
);
return ob_get_clean();
}正如Rup在注释中所指出的,一个选项是将html连接到一个字符串变量,然后返回它。
function my_shortcode() {
$output = '';
$output .= 'Some HTML here';
$output .= '';
return $output;
}就我个人而言,我喜欢使用sprintf()在类似的情况下返回。我认为它使代码看起来很干净,并使添加逃避变得轻而易举。
function my_shortcode() {
return sprintf(
'
%s
%s
',
esc_html('Some HTML here'),
esc_html('Additional nested HTML')
);
}特别是对于列表,我倾向于构建一个列表项数组,该数组被内爆为一个字符串。但是,您可以使用相同的想法将各种HTML字符串推入数组中,在输出返回时将数组转换为一个字符串。
function my_shortcode() {
$list_items = array();
foreach ($some_array as $value) {
$list_items[] = sprintf(
'%s',
esc_html($value)
);
}
return '' . implode('', $list_items) . '';
}https://wordpress.stackexchange.com/questions/386787
复制相似问题