Run Image Attributes Pro Bulk Updater Programmatically

Image Attributes Pro updates image attributes such as image alt text and image title using it’s bulk updater. The bulk updater is designed to cycle through each image on your WordPress website and update it’s attributes.

The bulk updater is housed in the Bulk Updater tab of Image Attributes Pro and runs using Java Script as long as the browser tab is kept open.

Bulk_updater

If you have a use case where you need to run the Bulk Updater programmatically instead, the following function is for you.

/**
 * Run Image Attributes Pro Bulk Updater Programmatically
 * 
 * @param (int) $batch_size Defines the number of images that will be processed
 * in a single call to the function. Higher batch sizes can lead to PHP time outs. 
 * 
 * @author Arun Basil Lal
 */
function prefix_iap_run_bulk_updater( $batch_size = 10 ) {

	// Return while call is made from ajax.
	if ( wp_doing_ajax() ) {
		return;
	}

	// Return if Image Attributes Pro is not active.
	if ( ! function_exists( 'iaff_is_pro' ) || ! iaff_is_pro() ) {
		return;
	}

	// Return if all images are updated. 
	if ( iaff_count_remaining_images() === 0 ) {
		return;
	}

	if ( iaff_count_remaining_images() < $batch_size ) {
		$batch_size = iaff_count_remaining_images();
	}

	// Process one batch of images. 
	for ( $i = 0; $i < $batch_size; $i++ ) {
		
		// Retrieve Counter
		$counter = get_option('iaff_bulk_updater_counter');
		$counter = intval ($counter);

		global $wpdb;
		$image = $wpdb->get_row("SELECT ID, post_parent FROM {$wpdb->prefix}posts WHERE post_type='attachment' AND post_mime_type LIKE 'image%' ORDER BY post_date LIMIT 1 OFFSET {$counter}");

		// Die if no image
		if ($image === NULL) {
			return;
		}
		
		// Running the pro module
		iaffpro_auto_image_attributes_pro( $image, true );

		// Increment counter and update it
		$counter++;
		update_option( 'iaff_bulk_updater_counter', $counter );
	}
}

Things to note:

  • $batch_size determines the number of images processed in one call to the function. The value in the above example is 10 which means that 10 images will be processed for every call to the function.
  • A higher $batch_size means more images will be processed at one. But it will also increase the chance of a PHP time out. Use with caution.
  • You can add the above function in a PHP file / script and call the file as a cron job. Remember to load WordPress in that case. You can do it by adding require( 'wp-load.php' ); in the top of the file assuming you will be placing the file in the root directly of WordPress. Here is an example.