2

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);
1

This is working for me

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

  // if shortcode 'book' exists
  if ( preg_match_all( '/'. $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+)"/', $matches[3][$att], $book_id);

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

there is actually a much simpler way to achieve this. When the content is parsed by WP, it executes the shortcodes it finds in the content. As of WP 4.7 a new filter, do_shortcode_tag is triggered when a shortcode is replaced by its content. This is really useful to add additional content to the shortcode output based on the attributes found,

add_filter( 'do_shortcode_tag','add_my_script',10,3);
function enqueue_my_script($output, $tag, $attr){
  if('aShortcode' != $tag){ //make sure it is the right shortcode
    return $output;
  }
  if(!isset($attr['id'])){ //you can even check for specific attributes
    return $output;
  }
  $output.='<script> ... </script>';
  return $output;
}

alternatively, if you need to put something into the footer of your page, you could hook onto the wp_footer action within the above function either an an anonymous function or to fire another function in your file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.