很高兴听到你已经设法解决了这个问题。这里有几个示例,介绍如何从短代码返回html。
正如您已经发现的,您可以使用ob_start()
和ob_get_clean()
缓冲html。在它里面,您可以回显标记或退出PHP并编写纯HTML。
function my_shortcode() {
ob_start();
echo \'<div>some HTML here</div>\';
?>
<p>Or outside of the PHP tags</p>
<?php
return ob_get_clean();
}
如果短代码在一个主题内,那么您也可以使用
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 = \'<div>\';
$output .= \'Some HTML here\';
$output .= \'</div>\';
return $output;
}
就我个人而言,我喜欢使用
sprintf()
在类似情况下返回。我认为它使代码看起来干净,并使添加逃逸变得轻而易举。
function my_shortcode() {
return sprintf(
\'<div>
<p>%s</p>
<div>%s</div>
</div>\',
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(
\'<li>%s</li>\',
esc_html($value)
);
}
return \'<ul>\' . implode(\'\', $list_items) . \'</ul>\';
}