So in between battling puppy pee, I’ve also been fighting with regular expressions for the better part of the evening. To summarize, I hate regular expressions. I just don’t get the logic, never have, and just when I think something makes sense, I’m told that I forgot like eight different escape characters or special circumstances or whatever and I feel like I’m back at square one.
With that said, after my last geeky code post of this nature, I decided that I want to get in the habit that when I fight with something long enough, I at least post about it online, both to vent and also to share in case someone else encounters something similar in the future!
Anyways, the scenario is this – working in PHP with WordPress, writing a custom category template for a new site I’ve been building. In this case, I needed to be able to pull the first image tag out of a post so that essentially I could create a category view that simply showed POST TITLE/DATE/ETC, IMAGE, MORE LINK TO VIEW ENTIRE POST.
Quickly, the caveats:
- I know that there are plug-ins to do this, however using code directly in the template is far more efficient because this will really only affect a fraction of the posts.
- Those plug-ins basically just parse out the tags, which won’t work for me anyways because I’m using NextGen Gallery for my images, meaning that the syntax stored in post is a shortcode like this – [singlepic id=123 w=550 h=413 float=center].
I fought with regular expressions for hours upon hours, but finally managed to come up with this:
(searching for this tag)
[singlepic id=123 w=550 h=413 float=center]
preg_match_all ('/(^\\[.*?\\])/is', get_the_content(), $matches);
$image = $matches[0]; $image = $image[0];
echo do_shortcode($image);
Basically it just looks for a tag in brackets at the very beginning of the post, which is my default format, however also meaning that it won’t get caught on anything if for whatever reason I end up using additional tags later on in the post. The first function does the actual search through the post content and throws the results into an array ($matches), with the second line extracting the tag out to a single variable and the final line executing it as a WordPress shortcode.
I’m still not entirely sure why I have to do line #2 twice – I guess between the preg_match_all() function and the data, it ends up as an array within an array, but after literally four hours of staring at this stupid thing, what you see above is officially the point where I said, “It works – good enough!”