如何让WordPress上传图片时自动添加Alt注释与图像描述

发布时间:2021-6-28 08:05

我们都知道搜索引擎对于图片的识别是比较弱的,给图片添加Alt注释和描述是至关重要的。但很多时候我们都会不经意之间给省略掉,这个对于图片的seo优化应该是非常不利的。

WordPress图片Alt注释

如何让WordPress上传图片时自动添加Alt注释与图像描述

那么,如何让WordPress上传图片时自动添加Alt注释与图像描述呢?网上很多杂七杂八的教程,但加结果都有点不尽人意。今天Ourboke联盟就给大家讲述一种纯代码的解决方式,一起来学习学习:

    add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
    function my_set_image_meta_upon_image_upload( $post_ID ) {
     
    	// Check if uploaded file is an image, else do nothing
     
    	if ( wp_attachment_is_image( $post_ID ) ) {
     
    		$my_image_title = get_post( $post_ID )->post_title;
     
    		// Sanitize the title:  remove hyphens, underscores & extra spaces:
    		$my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ',  $my_image_title );
     
    		// Sanitize the title:  capitalize first letter of every word (other letters lower case):
    		$my_image_title = ucwords( strtolower( $my_image_title ) );
     
    		// Create an array with the image meta (Title, Caption, Description) to be updated
    		// Note:  comment out the Excerpt/Caption or Content/Description lines if not needed
    		$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
    		);
     
    		// Set the image Alt-Text
    		update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
     
    		// Set the image meta (e.g. Title, Excerpt, Content)
    		wp_update_post( $my_image_meta );
     
    	} 
    }

方法很简单,将以上代码添加到当前主题函数模板functions.php中即可。

原理是此代码可以过滤掉图片名称中的空格等多余元素,对之前上传的图片无效。怎么样,是不是非常的简单便捷,你也赶快去试试吧!

WordPress纯代码实现文章相关推荐功能 WordPress

WordPress纯代码实现文章相关推荐功能

这两天准备把的相关推荐功能进行了重写,将原来的文章相关推荐功能做了自我感觉非常优秀的改进,相比用其它 WordPress 相关文章推荐的插件来说,我更喜欢自己来折腾,经过这一番的重写 WordPres...