Igor Simic
7 years ago

How to get all shordcodes from post in Wordpress


To extract all shordcodes from post there is a wordpress built in function which can be used in this case: 
get_shortcode_regex()
this function will collect all registered shortcodes, and using regex we can check does targeted post contains one of those shortcodes:
preg_match_all('/'.$pattern.'/uis', $post->post_content, $matches);

So the complete function to get the list of shortcodes with parameters from specific post could look like this:
function prefix_get_all_shortocodes_from_post($post_id){
   global $post;
   $post = get_post ($post_id);// get current post
   
   $pattern = get_shortcode_regex();// get all registered shortcodes
   preg_match_all('/'.$pattern.'/uis', $post->post_content, $matches);

   return $matches;
}
This function will return array like this:
Array
(
    [0] => Array
        (
            [0] => [slide-anything id="213"]
            [1] => [gallery ids="186,185,187,184,183,181,182"]
        )

    [1] => Array
        (
            [0] => 
            [1] => 
        )

    [2] => Array
        (
            [0] => slide-anything
            [1] => gallery
        )

    [3] => Array
        (
            [0] =>  id="213"
            [1] =>  ids="186,185,187,184,183,181,182"
        )

    [4] => Array
        (
            [0] => 
            [1] => 
        )

    [5] => Array
        (
            [0] => 
            [1] => 
        )

    [6] => Array
        (
            [0] => 
            [1] => 
        )

)