Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

How I can handle this shortcode:
[my_gallery]
img01.jpg
img02.jpg
img03.jpg
img04.jpg
[/my_gallery]

I can't understand how to write a function, to handle image files name.

share|improve this question
add comment

migrated from stackoverflow.com May 26 '11 at 14:01

This question came from our site for professional and enthusiast programmers.

1 Answer

up vote 1 down vote accepted

Are you going to put newlines in there between each image? or just spaces? I'll put in both for this example, checking if there's a newline.

You would want something like this in your functions.php:

add_shortcode('my_gallery', 'gallery_function');
function gallery_function($atts, $code=''){
   $files=preg_split( '/\s+/', $code ); // Added in from Jan's comment.

   foreach($files as $img){
      if($img=="")
          continue; // ensures that no empty items from the split have entered in, since that is possible with the preg_split
      //handle each filename in here.
   }
}

It's not perfect.. if you use both spaces and newlines in your shortcode, it'll mess things up - though that could be dealt with in more detail inside the function.

Hope this helps.

share|improve this answer
1  
With a regular expression you can split on either a newline or a space character. preg_split( '/[\n ]+/', $code ), or even just preg_split( '/\s+/', $code ) to split on any whitespace character. –  Jan Fabry May 26 '11 at 15:42
    
Thanks for that Jan, i'm not all that confident in my regex skills, so I opted not to go that route for fear of giving a faulty example. But yeah that would be the preferred route is to add in regex to cover different ways of doing it. –  Mike May 26 '11 at 16:08
    
Updated to include the preg_split with whitespace, then put in a check to ensure there was actually a potential file name in the loop. –  Mike May 26 '11 at 16:17
    
@Mike: If you use the preg_split() you don't need to detect the marker either. –  Jan Fabry May 26 '11 at 16:19
    
@Jan: Ah! Thanks :) I completely forgot about that, updated. –  Mike May 26 '11 at 16:39
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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