织梦DEDEcms文章内容中的图片自动添加ALT和title属性为文章标题

DEDEcms文章中的图片自动添加ALT属性方法一

打开Include/ arc.archives.class.php

查找:

@SetSysEnv($this->Fields['typeid'],$this->Fields['typename'],$this->Fields['id'],$this->Fields['title'],'archives');

在上面代码后面添加:

//替换图片Alt和title为文档标题
$this->Fields['body'] = str_ireplace(array('altalt=""','alt=\'\''),'',$this->Fields['body']);
$this->Fields['body'] = preg_replace("@ [\s]{0,}alt[\s]{0,}=[\"'\s]{0,}[\s\S]{0,}[\"'\s] @isU"," ",$this->Fields['body']);
$this->Fields['body'] = str_ireplace("<img " ,"<img alt=\"".$this->Fields['title']."\" title=\"".$this->Fields['title']."\" ",$this->Fields['body']);
$this->Fields['imgurls'] = str_ireplace(array('altalt=""','alt=\'\''),'',$this->Fields['imgurls']);
$this->Fields['imgurls'] = preg_replace("@ [\s]{0,}alt[\s]{0,}=[\"'\s]{0,}[\s\S]{0,}[\"'\s] @isU"," ",$this->Fields['imgurls']);
$this->Fields['imgurls'] = str_ireplace("<img " ,"<img alt=\"".$this->Fields['title']."\" ",$this->Fields['imgurls']);

上面是修改默认的模板标签:{dede:field.body/} ,如果是其它字段,可以修改$this->Fields['body'] 为其它的字段名。

效率说明:使用了正则处理,会降低一些生成速度,如果数据量小,则可以忽略。

DEDEcms文章中的图片自动添加ALT和title方法二

不修改系统核心文件,只用在模板里面调用就行了。把内容页的{dede:field.body/}调用标签替换为

{dede:field.body runphp=yes}
global $dsql,$id,$aid;
$myid = isset($id) ? $id : $aid;
$row = $dsql->GetOne("SELECT title FROM `#@__archives` WHERE id=$myid");
$title = $row['title'];
$str = @me;
$search = '/(<img.*?)alt=(["\'])?.*?(?(2)\2|\s)([^>]+>)/is';
$search1 = '/(<img.*?)title=(["\'])?.*?(?(2)\2|\s)([^>]+>)/is';
$content = preg_replace($search,'$1$3',$str);
$content = preg_replace($search1,'$1$3',$content);
@me = str_replace('<img', "<img alt='{$title}' title='{$title}'", $content);
{/dede:field.body}

 

THE END