Add keywords to images automatically

Add the following to the functions.php of your theme:

/**********************************************************************************/
/* images filters voor titel en alt                                               */
/**********************************************************************************/

add_filter('image_send_to_editor', 'filter_images_alt_to_editor', 10, 2);
function filter_images_alt_to_editor($html, $id) {
    global $post;

    $txtToAdd = 'This is some text to add always';

    $newAlt = sprintf('%1$s - %2$s - %3$s', 
       get_the_title($id), 
       $post->post_title , 
       $txtToAdd
    );

    return str_replace('alt=""','alt="' . $newAlt . '"', $html);
}

add_filter('wp_get_attachment_image_attributes', 'filter_title_alt_to_images', 10, 2);
function filter_title_alt_to_images($attributes, $attachment){
    global $post;

    if ( !isset( $attributes['alt'] ) || '' === $attributes['alt'] ) {

        $txtToAdd = 'This is some text to add always';

        $newAlt = sprintf('%1$s - %2$s - %3$s', 
            get_the_title($attachment->ID), 
            $post->post_title , 
            $txtToAdd
        );

        $attributes['alt'] = $newAlt;
        $newTitle = sprintf('%1$s - %2$s', 
            get_the_title($attachment->ID), 
            $post->post_title
        );

        $attributes['title']=$newTitle;
    }

    return $attributes;
}
Last update: October 22nd at 8:33am