Think about a post content like below:
[shortcode a="a_param"]
... Some content and shortcodes here
[shortcode b="b_param"]
.. Again some content here
[shortcode c="c_param"]
I have a shortcode that takes 3 or more parameters. I want to find out how many times the shortcode is used at the content and its parameters in an array like,
array (
[0] => array(a => a_param, b=> null, c=>null),
[1] => array(a => null, b=> b_param, c=>null),
[2] => array(a => null, b=> null, c=>c_param),
)
I need to do this in the_content filter, wp_head filter or something similar.
How can I do this ?
Thank you,
In wordpress get_shortcode_regex() function returns regular expression used to search for shortcodes inside posts.
$pattern = get_shortcode_regex();
Then preg_match the pattern with the post content
if ( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches ) )
If it return true, then extracted shortcode details are saved in $matches variable.
Try
global $post;
$result = array();
//get shortcode regex pattern wordpress function
$pattern = get_shortcode_regex();
if ( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches ) )
{
$keys = array();
$result = array();
foreach( $matches[0] as $key => $value) {
// $matches[3] return the shortcode attribute as string
// replace space with '&' for parse_str() function
$get = str_replace(" ", "&" , $matches[3][$key] );
parse_str($get, $output);
//get all shortcode attribute keys
$keys = array_unique( array_merge( $keys, array_keys($output)) );
$result[] = $output;
}
//var_dump($result);
if( $keys && $result ) {
// Loop the result array and add the missing shortcode attribute key
foreach ($result as $key => $value) {
// Loop the shortcode attribute key
foreach ($keys as $attr_key) {
$result[$key][$attr_key] = isset( $result[$key][$attr_key] ) ? $result[$key][$attr_key] : NULL;
}
//sort the array key
ksort( $result[$key]);
}
}
//display the result
print_r($result);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With