Ashley Cameron Design

Ashley Cameron Design

Shop the Creative Design Market

Good morning
Wordpress Function Add Alt And Title To Image Without Plugin

Function to Add alt tag and title tag to WordPress Images Without Using a Plugin

PHPSnippetsWordPress

About a 1 minute read

"I am always doing what I cannot do yet, in order to learn how to do it."

Vincent Van Gogh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
/* Output images with alt and optional title text */
function acd_add_img_title( $attr, $attachment = null ) {
    $img_title = trim( strip_tags( $attachment->post_title ) );
    $img_title = str_replace("-", " ", $img_title); //remove hyphens
    $img_title = str_replace("_", " ", $img_title); //remove underscores
    $img_title = preg_replace('/[0-9]+/', '', $img_title); //remove numbers
   
    $attr['title'] = $img_title; //add image title attribute
    // or get the title instead of image title $attr['title'] = the_title_attribute( 'echo=0' );
    $attr['alt'] = $img_title; //add alt attribute
    return $attr;
}
add_filter( 'wp_get_attachment_image_attributes','acd_add_img_title', 10, 2 );