Search content for shortcodes and get parameters

In content I can have multiple shortcodes like [book id="1"] [book id="14" page="243"]

Is there any help method with which I can search the content for that shortcode and get its parameters? I need to get IDs so I can call WP_Query and append the Custom Post Types titles at the end.

function filter_books( $content ) {

// get all shortcodes IDs and other parameters if they exists
...

return $content;
}
add_filter( 'the_content', 'filter_books', 15 );

I tried using following code but var_dump($matches) is empty and if it would work I am not sure how would I get parameters (https://stackoverflow.com/questions/23205537/wordpress-shortcode-filtering-the-content-modifies-all-posts-in-a-list)

  $shortcode="book";
  preg_match('/\['.$shortcode.'\]/s', $content, $matches);

2 Answers
2

This is working for me

  $shortcode="book";
  $pattern = get_shortcode_regex();

  // if shortcode 'book' exists
  if ( preg_match_all( "https://wordpress.stackexchange.com/". $pattern .'/s', $post->post_content, $matches )
    && array_key_exists( 2, $matches )
    && in_array( $shortcode, $matches[2] ) )  {
   $shortcode_atts = array_keys($matches[2], $shortcode);

 // if shortcode has attributes
 if (!empty($shortcode_atts)) {
  foreach($shortcode_atts as $att) {
    preg_match('/id="(\d+)"https://wordpress.stackexchange.com/", $matches[3][$att], $book_id);

    // fill the id into main array
    $book_ids[] = $book_id[1];
  }
}
...

Leave a Comment