Reputation: 476
My purpose is to go from something like this, as taken from post_content
:
[video width="1080" height="1920" webm="http://path/file.webm" autoplay="true"][/video]
to an array like this:
Array(
width=>1080,
height=>1920,
webm=>"http://path/file.webm",
autoplay=>"true"
);
Of course with more or less pairs depending on what the user has entered in the video shortcode.
I have read the Shortcode_API and the instructions about shortcode_atts
. Nowhere I can find an easy explanation on how to get those attributes in a form of an array.
Despite what people keep suggesting I cannot use shortcode_atts
because this wordpress function requires the attributes to be already in an array!
I know how to get the above more or less done with regex. But is there any wordpress obvious way to turn shortcode attributes into an array? I know there should be.
As an example, this doesn't work:
shortcode_atts( array(
'width' => '640',
'height' => '360',
'mp4' => '',
'autoplay' => '',
'poster' => '',
'src' => '',
'loop' => '',
'preload' => 'metadata',
'webm' => '',
), $atts);
because $atts is supposed to be an array, but all I have is a string from $post_content
which looks like this:
[video width="1080" height="1920" webm="http://path/file.webm" autoplay="true"][/video]
Please note: I am not implementing a shortcode functionality or anything like that. I just need to read a wordpress video shortcode as added in post content.
Upvotes: 0
Views: 1296
Reputation: 1122
It looks to me that (at least in version 4.7) that the function you specify with add_shortcode() will put the shortcode parameters into an array:
If you add the shortcode like this:
add_shortcode('my_shortcode_name', 'my_shortcode_function');
Then the 'my_shortcode_function' like this will have an array of the attributes:
function my_shortcode_function($atts) {
// this will print the shortcode's attribute array
echo '<pre>';print_r($atts);echo '</pre>';
}
...Rick...
Upvotes: 0
Reputation: 1680
Here's a very compact solution with a regular expression:
<?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"
)
Upvotes: 1
Reputation: 476
If anyone's interested the answer to the above is the function shortcode_parse_atts
as described here.
Upvotes: 1