我們?cè)诤笈_(tái)上傳文件時(shí)會(huì)碰到上傳的圖片會(huì)自動(dòng)加上高度與寬度了,那么有時(shí)我們并不需要這個(gè)東西要怎么取消呢?下面我們一起來看看我總結(jié)的兩種方法.
要求,如,在桌面設(shè)備上,圖片使用的是以下的HTML代碼:
<img src="abc.png" alt="abc" width="580" height="267" />
在移動(dòng)設(shè)備端,因?yàn)槠聊欢急容^小,如果要讓圖片自適應(yīng)屏幕,我們應(yīng)當(dāng)把width和height屬性去除,不然圖片可能會(huì)比屏幕大,代碼如下:
<img src="abc.png" alt="abc" />
方法一:將下面代碼復(fù)制到當(dāng)前主題的 functions.php 文件中:
- add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
- add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );
- function remove_width_attribute( $html ) {
- $html = preg_replace( '/(width|height)="/d*"/s/', "", $html );
- return $html;
- }
方法二:代碼如下:
- // 自適應(yīng)圖片刪除width和height,by Ludou
- function ludou_remove_width_height_attribute($content){
- preg_match_all("/<[img|IMG].*?src=[/'|/"](.*?(?:[/.gif|/.jpg|/.png/.bmp]))[/'|/"].*?[//]?>/", $content, $images);
- if(!emptyempty($images)) {
- foreach($images[0] as $index => $value){
- $new_img = preg_replace('/(width|height)="/d*"/s/', "", $images[0][$index]);
- $content = str_replace($images[0][$index], $new_img, $content);
- }
- }
- return $content;
- }
- // 判斷是否是移動(dòng)設(shè)備瀏覽
- if(wp_is_mobile()) {
- // 刪除文章內(nèi)容中img的width和height屬性
- add_filter('the_content', 'ludou_remove_width_height_attribute', 99);
- }
這樣我再試一下是不是達(dá)到想要的結(jié)果了.
新聞熱點(diǎn)
疑難解答
圖片精選