DedeCMS为文章图片自动添加ALT属性为标题(二)

只有经受过冰霜的人,才会领悟太阳的温暖,只有饱尝人生艰辛的人,才会懂得生命的可贵。早安!

在《DedeCMS为文章图片自动添加ALT属性为标题》一文中,余斗教大家如何在include/ arc.archives.class.php中添加代码来实现为图片添加alt属性为文章标题,这个方法在PHP7以上的环境中不太行,可能是织梦对PHP7.0支持不够的原因吧!

恰好在《DedeCMS使用扩展函数调用任意数据表的方法》中,说到通过自定义函数来实现我们需要的任何功能,那么,同理,我们可以用自定义函数来实现为文章图片自动添加ALT属性为标题。

首先修改/include/extend.func.php,里面的把这段代码加进去:

	
	    //文章body优化替换
	    function replaceurl($newurl)
	    {
	    global $dsql,$id;
	    //获取图片附加表imgurls字段内容进行处
	    $row = $dsql->GetOne("SELECT title FROM dede_archives where id=$id");
	    //替换图片Alt为文档标题
	    $newurl=str_ireplace(array('alt=""",'alt=\&;\&;'),'',$newurl);
	    $newurl=preg_replace("@ [\s]{0,}alt[\s]{0,}=[\&;'\s]{0,}[\s\S]{0,}[\&;'\s] @isU"," ",$newurl);
	
$newurl=str_ireplace("<img " ,"<img alt=\&;".$row['title']."\&;",$newurl); //去掉结尾空格 $newurl=str_ireplace("/","/",$newurl); $newurl=str_ireplace("/>","/>",$newurl); return $newurl; }

然后在我们需要调用文章内容的地方加上调用代码:

	
	{dede:field.body function='replaceurl(@me)'/}
	

最后补充,由于之前在《DedeCMS文章页去img图片width和height属性》一文中,余斗也是通过修改include/ arc.archives.class.php文件来实现去高宽属性,既然我们今天用自定义函数实现了替换alt属性,那么也可以把去高宽属性的这个功能加进去,完整代码如下:

	
	  //文章body优化替换
	  function replaceurl($newurl)
	  {
	  global $dsql,$id;
	  //获取图片附加表imgurls字段内容进行处
	  $row = $dsql->GetOne("SELECT title FROM dede_archives where id=$id");
	  //去掉img的width和height
	  $newurl=preg_replace('/style=\&;width\:(.*)\&;/','',$newurl);
	  //替换图片Alt为文档标题
	  $newurl=str_ireplace(array('alt=""",'alt=\&;\&;'),'',$newurl);
	  $newurl=preg_replace("@ [\s]{0,}alt[\s]{0,}=[\&;'\s]{0,}[\s\S]{0,}[\&;'\s] @isU"," ",$newurl);
	  $newurl=str_ireplace("<img " ,"<img alt=\&;".$row['title']."\&;",$newurl);
	  //去掉结尾空格
	  $newurl=str_ireplace("/","/",$newurl);
	  $newurl=str_ireplace("/>","/>",$newurl);
	  return $newurl;
	  }
	

文章内容调用代码不变!

以上就是DedeCMS为文章图片自动添加ALT属性为标题(二)。让一个人从你面前消失的最快方法,是你自己先转过身去。更多关于DedeCMS为文章图片自动添加ALT属性为标题(二)请关注haodaima.com其它相关文章!

标签: DedeCMS ALT