Just wanted to say, 6 months after the fact that this totally saved me from a mental breakdown today. After 1.5 hours of scouring this site I found this, thought I’d document what I was trying to do and what I did to fix it.
First of all, I’m using WordPress as a CMS in this case, with no blog. Each page of the CMS uses a unique banner image, and I wanted to put this in my template to have it automated. Here’s what I originally started with:
<img src="images/<?php the_title(); ?>.jpg" alt=" <?php the_title(); ?> " />
which outputed:
<img src="images/Contact Us.jpg" alt=" Contact Us " />
This would work, but isn’t even close to being nice code, so I ended up going with:
<img src="images/banners/<?php
$title = get_the_title();
$loweredTitle = strtolower($title);
echo str_replace(" ", "_", $loweredTitle);
?>.jpg" alt=" <?php the_title(); ?> " />
which outputs:
<img src="media/images/banners/contact_us.jpg" alt=" Contact Us " />
Excellence! It turns out essentially how %postname% would, but because I had the option I used underscores (“_”) instead of dashes (“-“).
Thanks Kaf, and hopefully this extended documentation will help someone in the future!