我的目的是从这样的东西,从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的文章。对于如何以数组的形式获取这些属性,我找不到一个简单的解释。
尽管人们一直建议我不能使用shortcode_atts,因为这个wordpress函数要求属性已经在数组中了!
我知道如何用regex或多或少地完成上述工作。但是,有什么明显的方法可以将短代码属性转换为数组呢?我知道应该有。
举个例子,这是行不通的:
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视频短片,因为添加在帖子内容。
发布于 2016-02-14 10:22:32
如果有人感兴趣,那么上面的答案是shortcode_parse_atts函数,如这里所描述的那样。
发布于 2016-02-14 10:38:00
下面是一个非常紧凑的解决方案,其中有一个正则表达式:
代码
<?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" )
发布于 2016-12-26 20:28:07
在我看来(至少在4.7版中),您用add_shortcode()指定的函数将把短代码参数放入数组中:
如果您添加了这样的短代码:
add_shortcode('my_shortcode_name', 'my_shortcode_function');然后像这样的'my_shortcode_function‘将有一个属性数组:
function my_shortcode_function($atts) {
// this will print the shortcode's attribute array
echo '<pre>';print_r($atts);echo '</pre>';
}...Rick...
https://stackoverflow.com/questions/35390284
复制相似问题