1

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.

1 Answer 1

1

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.

6
  • 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, 2011 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, 2011 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, 2011 at 16:17
  • @Mike: If you use the preg_split() you don't need to detect the marker either.
    – Jan Fabry
    May 26, 2011 at 16:19
  • @Jan: Ah! Thanks :) I completely forgot about that, updated.
    – Mike
    May 26, 2011 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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