Capitalize Shortcode Value on Output

I wrote this shortcode to take a filename I specify and output it as an image with title and alt tags:

function cwc_pkmn($atts) {
    extract(shortcode_atts(array(
        "name" => 'http://',
    ), $atts));
    return '<img src="https://wordpress.stackexchange.com/path/to/file/".$name.'.png" alt="'.$name.'" title="'.$name.'" />';
}
add_shortcode("pkmn", "cwc_pkmn");

All of my filenames are lowercase with a “-” between words. Is it possible to have the output capitalize each letter following a – and replace the – with spaces? So right now, when I do the shortcode above like this:

[pkmn name="mr.-deeds"]

I get this as the output:

<img src="https://wordpress.stackexchange.com/path/to/file/mr.-deeds.png" alt="mr.-deeds" title="mr.-deeds">

But is it possible to have the output do this instead with the title and alt tags?:

<img src="https://wordpress.stackexchange.com/path/to/file/mr.-deeds.png" alt="Mr. Deeds" title="Mr. Deeds">

Thank you so much!

2 Answers
2

Try this out. . .

function cwc_pkmn( $atts = array(), $content="" )
{
    // ------------------------
    // Settings:
    $path="https://wordpress.stackexchange.com/path/to/file/";
    $ext="png";
    // ------------------------

    // Shortcode input:
    $atts = shortcode_atts(
        array( 'name' => '' ),
        $atts,
        'pkmn_shortcode'
    );

    // Sanitize input:
    $name          =  esc_attr( $atts['name'] );

    // Init:
    $words_ucfirst = array();

    // Capitalize the first letter in each word:
    $words         = explode( '-', $name );

    foreach( $words as $word )
    {
        $words_ucfirst[] =  ucfirst( $word );
    }

    $name_mod = esc_attr( join( ' ', $words_ucfirst ) );

    return sprintf( '<img src="https://wordpress.stackexchange.com/questions/151323/%s%s.%s" alt="%s" title="%s" />',
        $path,
        $name,
        $ext,
        $name_mod,
        $name_mod
    );
}

add_shortcode( 'pkmn', 'cwc_pkmn' );

Leave a Comment