Ashley Cameron Design

Ashley Cameron Design

Shop the Creative Design Market

Goodnight
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

"The art of living… is neither careless drifting on the one hand nor fearful clinging to the past on the other. It consists in being sensitive to each moment, in regarding it as utterly new and unique, in having the mind open and wholly receptive."

Alan Watts

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 );