If you wish to update the attributes of every image in a page, post, WooCommerce product or any other custom post type when the post is published or updated, add the following code to the functions.php
of your active theme.
This can be used as a fallback to make sure that the image attributes are always exactly the way you like it. This is useful on websites with multiple authors where implementing a standard structure for image attributes might be required.
Image attributes will be updated as per the settings used in Bulk Updater Settings
tab of Image Attributes Pro.
/**
* Update image attributes as per the Bulk Updater Settings of Image Attributes Pro
* when a post is saved or updated.
*
* @author Arun Basil Lal
* @link https://imageattributespro.com/update-image-attributes-on-save-post/
*/
function prefix_iap_update_image_attributes_on_save_post( $post_id ) {
if ( ! function_exists( 'iaffpro_update_attributes_in_post_by_post_id' ) ) {
return;
}
// post_id from save_post will be the ID of the revision.
// So here we are finding parent post_id.
if ( $post_parent_id = wp_get_post_parent_id( $post_id ) ) {
$post_id = $post_parent_id;
}
/**
* iaffpro_update_attributes_in_post_by_post_id() will call save_post again.
* To prevent this, unhook action right before.
*
* @link https://developer.wordpress.org/reference/hooks/save_post/#avoiding-infinite-loops
*/
remove_action( 'save_post', 'prefix_iap_update_image_attributes_on_save_post' );
iaffpro_update_attributes_in_post_by_post_id( $post_id );
}
add_action( 'save_post', 'prefix_iap_update_image_attributes_on_save_post' );
Notes:
- Be mindful of the
Bulk Updater Behaviour
in theBulk Updater Settings
. If it’s set to preserve existing attributes, then attributes added during image upload will not be overwritten when the post is published / updated. - Requires Image Attributes Pro 3.0 and above.
- Codex: iaffpro_update_attributes_in_post_by_post_id()