WordPress上传图片时自动填充图片title和alt

tencent promotion
原创作者: Fengjiajun

WordPress上传图片时自动填充图片title和alt

默认情况,WordPress上传到媒体的图片title和alt为空,但是考虑到SEO,插入到文章或页面的图片必须要填写alt或者title,每张图片都要手动填写,效率太慢了。

下面的代码能够实现:

WordPress上传图片时,根据图片的名字自动填充图片title和alt等属性,拿去享用吧!

function my_set_image_meta_upon_image_upload( $post_ID ) {
    if ( wp_attachment_is_image( $post_ID ) ) {
        $my_image_title = get_post( $post_ID )->post_title;
        $my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ',  $my_image_title );
        $my_image_title = ucwords( strtolower( $my_image_title ) );
        $my_image_meta = array(
            'ID'		=> $post_ID,			// Specify the image (ID) to be updated
            'post_title'	=> $my_image_title,		// Set image Title to sanitized title
            'post_excerpt'	=> $my_image_title,		// Set image Caption (Excerpt) to sanitized title
            'post_content'	=> $my_image_title,		// Set image Description (Content) to sanitized title
        );
        update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
        wp_update_post( $my_image_meta );
    } 
}
add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );