如何呈现复杂的快捷码

时间:2021-04-17 作者:gottaGetLaid

我希望你们今天过得愉快。我正在开发一个视频播放器插件,里面有自定义的短代码等等,但是我在短代码渲染方面遇到了问题。目前,我的短代码内容是用echo呈现的,它工作得很好,但它不会在页面内容中呈现,所以我必须以某种方式将其更改为return方法,但它内部有foreach循环和if else语句,所以我不能只做return \'<ul> \'.foreach($x as $s){}.\' </ul> \'; 诸如此类,你们知道解决这个问题的方法吗?我还尝试将所有内容放置在函数中,并尝试在return中呈现它,如下所示:return \' \'.renderdata().\' \'; 这是可行的,但它不会在内容内部呈现。

这是我的shortcode函数

function myshortcode( $atts = array() ) {
    $data = [\'some array with video data\'];
    
    foreach($data as $d){
        echo "<div>$d</div>";
    }
}
add_shortcode(\'someshortcode\', \'myshortcode\'); 
非常感谢您的帮助,谢谢。

EDIT: I was able to handle the problem with PHP Output Buffering, thanks to WordPress Codex.

解决方案:

function myshortcode() {
    ob_start();
    // HTML here
    return ob_get_clean();
}

1 个回复
SO网友:Antti Koskinen

很高兴听到你已经设法解决了这个问题。这里有几个示例,介绍如何从短代码返回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>\';
}

相关推荐

Wordpress Vue Js Shortcodes

目前,我正在与Vue一起开发wordpress网站。js和wordpress REST API,找不到使用wordpress ShortCodeEx的解决方案:Contact Form 7 我一直在尝试这个例子,但它似乎对我不起作用Vue.js + AJAX Shortcode有没有人有过类似的问题?编辑:For ExampleIn regular wordpress我可以用这种方式使用联系人表单插件 <section class=\"container section__form display-