am3

PHP script to insert wp-image names as its ALT tag

Posted on Posted in PHP, Technology, wordpress

Here is the script for checking wordpress media images’s ALT tags. if any uploaded image ALT tag is not present then this script insert the media name as its ALT value.

Some times after uploading many media images in wordpress, we need to add the ALT value for these images one by one. Below is the script for doing the same for all wp-images in just one execution of script.

To run this script, create a file on the wordpress root named(image_alt.php). put below script into that file. and execute that file.


/*
Check media for alt tag. If not present then set post title as alt value.
Author : Arsh Sharma
website : http://webtechbuddies.com
*/
error_reporting(-1);
ini_set('display_errors', 'On');
include_once('../wp-load.php');
global $wpdb;
$sql = "select wp.ID, wp.post_title from wp_posts as wp 
where wp.post_type='attachment' and wp.post_mime_type like '%image%'";
$results = $wpdb->get_results($sql);
$count = 0;
foreach ($results as $result) {
	$attach_meta = get_post_meta($result->ID);
	if (!array_key_exists("_wp_attachment_image_alt",$attach_meta) || $attach_meta['_wp_attachment_image_alt'] != '') {
		$sql = "insert into wp_postmeta (post_id,meta_key,meta_value) values ('".$result->ID."','_wp_attachment_image_alt','".$result->post_title."')";
		$wpdb->query($sql);
	}
} 
echo "done";

That’s it.