How to extract WordPress shortcode attributes from post content
There are several ways of doing this: 1. Write your own snippet as you did above, insert the following in your "mu-plugins" folder
// [myplayer attr="your-value"]
function myplayer_func($atts) {
extract(shortcode_atts(array(
'title' => 'something',
'mp3' => 'another something',
'soundcloud' => 'something else',
), $atts));
return "attr= {$attr}";
}
add_shortcode('myplayer', 'myplayer_func');
Then
[myplayer title="something" mp3="another something" soundcloud="something else"]
in any post from anywhere including subdomains. 2. You can use plugins like Shortcoder and Global Content Blocks
Related videos on Youtube
jas7457
Updated on September 15, 2022Comments
-
jas7457 over 1 year
In my posts on WordPress I have an unknown number of shortcodes of type
my_player
that I created and correctly added hooks to. I was wondering if there is some type of WordPress function you can pass your content to and shortcode name, and it could give you an array of matched shortcodes with their attributes indexed by attribute name. Something like my code below...$matches = get_shortcode_matches($content, "my_player"); for($i = 0; $i < sizeof($matches); $i++) { $title = $matches[$i]['title']; $mp3 = $matches[$i]['mp3']; $soundcloud = $matches[$i]['soundcloud']; }
I know that when you create the hook for the shortcodes using the
add_shortcode()
function you can use these indexed values like I have above, but I need to have a function that can access them later and outside of the loop. Does WordPress have any such function? -
jas7457 over 10 yearsI already use those. That does not help extract any of the attributes and their values though.
-
jas7457 over 10 yearsI said that I already set up the hooks and the
add_shortcode()
function. I know that you can have it use this information from this function, but I want to have a function that gives the shortcode name, the content to search for, and returns an array of name-value pairs. Something similar to my code written in my original post. -
redanimalwar over 7 yearsUsing the horrible extract() function is discouraged in the WordPress coding standards. Just so you know.