Skip to main content
edited tags
Link
Pieter Goosen
  • 55.4k
  • 23
  • 115
  • 209
Source Link
Jon
  • 171
  • 2
  • 13

Capitilize Alt/Title Tag in Image HTML, Reorder HTML Output

Someone kindly wrote the two pieces of code at the end of this post for me a few years ago. I'm currently trying to modify them but am not having much luck after an hour of Googling and breaking Wordpress over and over.

Right now, the first code takes an upload-file-name.jpg and change it to "uploaded file name" for the image's alt and title tags. The second code adds rel="highslide" and class="highslide" to each image's link. This is what it outputs when you insert an image into Wordpress:

<a class="highslide" href="http://domain.com/wp/uploads/0215/the-name-of-the-file.jpg" rel="highslide"><img class=" alignright" title="the name of the file" src="http://domain.com/wp/uploads/0215/the-name-of-the-file-217x200.jpg" alt="the name of the file" width="217" height="200" /></a>

What I want to do is capitilize the first letter of each word in the image's alt and title tags so that it outputs to "The Name Of The File."

For the link HTML, I'd also like to move class="highslide" to the end so that it goes in the order of href, rel, then class. I couldn't figure out how to change the order of anything even when switching pieces of code around. I know it sounds super nitpicky to reorder it, but my writers and I do a lot of manual HTML editing, and this order is what we're used to doing in Wordpress.

For the image HTML, I'd like to do it in the order of src, height, width, alt, title, then class.

I hope others can use these cool codes too! Thank you!

/** USE FILENAME FOR ALT AND TITLE TAGS WHEN INSERTING */
function wpse_120228_seomadness($html, $id, $caption, $title, $align, $url, $size, $alt) {

    $alttitle = str_replace('-', ' ', $alt);
    $img      = get_image_tag($id, $alttitle, $alttitle, $align, $size);
    $html     = '<a href="' . esc_attr($url) . '">' . $img . '</a>';

    return $html;
}
add_filter( 'image_send_to_editor', 'wpse_120228_seomadness', 10, 9 );


/** ADD HIGHSLIDE CLASSES TO HYPERLINKED IMAGES */
function add_highslide_attr( $html ) {
    preg_match_all('/(<a[^>]*>)(.*)/i', $html, $result);

    if( !isset($result) || !isset($result[1][0]) || ! $result[1][0] )
        return $html;

    $anchor = $result[1][0];

    if( strstr($anchor, 'rel=') )
        $anchor = str_replace('rel="', 'rel="highslide ', $anchor);
    else
        $anchor = str_replace('href=', 'rel="highslide" href=', $anchor);

    if( strstr($anchor, 'class=') )
        $anchor = str_replace('class="', 'class="highslide ', $anchor);
    else
        $anchor = str_replace('href=', 'class="highslide" href=', $anchor);

    $html = $anchor . $result[2][0];

    return $html;
}
add_filter( 'image_send_to_editor', 'add_highslide_attr', 10 );