WordPress上传图片时自动将图片重命名为文章标题

admin wordpress评论203
WordPress上传图片时自动将图片重命名为文章标题

Wordpress上传图片时自动将图片重命名为文章标题

在文章编辑时上传添加图片,自动将图片重命名为文章标题,并自动填充图片ATL、说明、替代文本、描述等相关信息。
将下面代码添加到当前主题函数模板functions.php中:

function file_renamer( $filename ) {
	$info = pathinfo( $filename );
	$ext  = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
	$name = basename( $filename, $ext );
	if( $post_id = array_key_exists( "post_id", $_POST) ? $_POST["post_id"] : null ) {
		if($post = get_post($post_id)) {
			return $post->post_title . $ext;
		}
	}
 
	$my_image_title = $post;
	$file['name'] = $my_image_title  . - uniqid() . $ext; // uniqid method
	// $file['name'] = md5($name) . $ext; // md5 method
	// $file['name'] = base64_encode( $name ) . $ext; // base64 method
	return $filename;
}
 
add_filter( 'sanitize_file_name', 'file_renamer', 10, 1 );
 
// 上传时自动设置图像标题、替代文本、标题和描述
add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
function my_set_image_meta_upon_image_upload( $post_ID ) {
 
	// 检查上传的文件是否是图片
	if ( wp_attachment_is_image( $post_ID ) ) {
 
		if( isset( $_REQUEST['post_id'] ) ) {
			$post_id = $_REQUEST['post_id'];
		} else {
			$post_id = false;
		}
 
		if ( $post_id != false ) {
			$my_image_title = get_the_title( $post_id );
		} else {
			$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,             // ID
			'post_title'    => $my_image_title,  // 图像标题
			'post_excerpt'  => $my_image_title,  // 图像说明
			'post_content'  => $my_image_title,  // 图像描述
		);
 
		// 添加图像 Alt
		update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
 
		// 添加标题、说明、描述
		wp_update_post( $my_image_meta );
	}
}

注意:上面的方法只适合在文章编辑页面使用,如果在媒体库上传无效。另外,图片名称为中文貌似有的主机环境并不支持。文章源自小虫博客-https://www.xczi.cn/wordpress/696.html 文章源自小虫博客-https://www.xczi.cn/wordpress/696.html

admin


  • ·版权声明·



    1、本站文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系客服进行删除处理。
    2、本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
    3、如有侵权请邮件admin@xczi.cn与我们联系处理。敬请谅解!


  • 转载请务必保留本文链接:WordPress上传图片时自动将图片重命名为文章标题-https://www.xczi.cn/wordpress/696.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: