从wordpress视频短代码中读取和提取属性?

时间:2016-02-14 09:32:42

标签: php wordpress attributes extract shortcode

我的目的是从post_content

取得这样的东西
[video width="1080" height="1920" webm="http://path/file.webm" autoplay="true"][/video] 

到这样的数组:

Array( 
    width=>1080, 
    height=>1920,
    webm=>"http://path/file.webm",
    autoplay=>"true"
);

当然,根据用户在视频短代码中输入的内容,可以使用更多或更少的对。

我已阅读Shortcode_API和关于shortcode_atts的{​​{3}}。无处可以找到关于如何以数组形式获取这些属性的简单解释。

尽管人们一直在暗示我无法使用shortcode_atts,因为这个wordpress函数要求已经在数组中的属性!

我知道如何使用正则表达式或多或少完成上述操作。但有没有任何wordpress明显的方法将短代码属性转换为数组?我知道应该有。

例如,这不起作用:

shortcode_atts( array(
                'width'    => '640',
                'height'   => '360',
                'mp4'   => '',
                'autoplay' => '',
                'poster'   => '',
                'src'      => '',
                'loop'     => '',
                'preload'  => 'metadata',
                'webm'   => '',
        ), $atts);

因为$ atts应该是一个数组,但我所拥有的只是来自$post_content的字符串,如下所示:

[video width="1080" height="1920" webm="http://path/file.webm" autoplay="true"][/video] 

请注意:我没有实现短代码功能或类似的东西。我只需读取在帖子内容中添加的wordpress视频短代码。

3 个答案:

答案 0 :(得分:1)

如果有人对上述问题的答案感兴趣,请按here所述的函数shortcode_parse_atts

答案 1 :(得分:1)

这是一个非常紧凑的解决方案,带有正则表达式:

代码

<?php
    $input = '[video width="1080" height="1920" webm="http://path/file.webm" autoplay="true"][/video]';

    preg_match_all('/([A-Za-z-_0-9]*?)=[\'"]{0,1}(.*?)[\'"]{0,1}[\s|\]]/', $input, $regs, PREG_SET_ORDER);
    $result = array();
    for ($mx = 0; $mx < count($regs); $mx++) {
        $result[$regs[$mx][1]] = is_numeric($regs[$mx][2]) ? $regs[$mx][2] : '"'.$regs[$mx][2].'"';
    } 

    echo '<pre>'; print_r($result); echo '</pre>';
?>

结果

Array [width] => 1080 [height] => 1920 [webm] => "http://path/file.webm" [autoplay] => "true" )

答案 2 :(得分:0)

在我看来(至少在4.7版本中)你用add_shortcode()指定的函数会将短代码参数放入数组中:

如果您添加如下的短代码:

    add_shortcode('my_shortcode_name', 'my_shortcode_function');

然后是&#39; my_shortcode_function&#39;像这样将有一个属性数组:

function my_shortcode_function($atts) {
// this will print the shortcode's attribute array
echo '<pre>';print_r($atts);echo '</pre>';
}

... ...瑞克

相关问题