I am trying to preview a NextGen gallery on my main page (and category pages) to show a single image from the gallery on the main page next to the text from the post that normally shows up. I have found examples of PHP that get the images from a gallery given a gallery ID. In my loop I have a current post. What I cannot figure out is how to, given a post, get the attributes of the [nggallery] short code.

In other words for each post with a NextGEN gallery I need the id value form the short code. For example if the post contains [nggallery id=50] I need the value 50.

How can I get that information from a post?

I was hoping to find the solution in the source code of the next gen plug-in but of course that code registered a short code handler and lets WP call them back. There are no examples in their source code where they parse a post looking for their short code.

3 Answers
3

Your solution has helped me find an answer to my own problem of getting the attribute of a certain shortcode, but I fear there may be an issue with your approach.

You’re using preg_match to check the post_content, which will only return 1 match. If you have a post that has multiple shortcodes in it, it will only return the first one, which may not be the one you’re looking for.

Instead, you should use preg_match_all, then loop through the regex_matches array to check for the shortcode you need.

Also, you don’t need to use str_replace to remove the quotes from the string. WordPress has a built-in function shortcode_parse_atts which takes that a string of parameters (in your case it would be $regex_matches[3]) as an argument and outputs an array. This would also spare you the use of wp_parse_args function.

Leave a Reply

Your email address will not be published. Required fields are marked *