我們在后臺上傳文件時會碰到上傳的圖片會自動加上高度與寬度了,那么有時我們并不需要這個東西要怎么取消呢?下面我們一起來看看我總結的兩種方法.
要求,如,在桌面設備上,圖片使用的是以下的HTML代碼:
<img src="abc.png" alt="abc" width="580" height="267" />
在移動設備端,因為屏幕都比較小,如果要讓圖片自適應屏幕,我們應當把width和height屬性去除,不然圖片可能會比屏幕大,代碼如下:
<img src="abc.png" alt="abc" />
方法一:將下面代碼復制到當前主題的 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;
- }
方法二:代碼如下:
- // 自適應圖片刪除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;
- }
- // 判斷是否是移動設備瀏覽
- if(wp_is_mobile()) {
- // 刪除文章內容中img的width和height屬性
- add_filter('the_content', 'ludou_remove_width_height_attribute', 99);
- }
這樣我再試一下是不是達到想要的結果了.
|
新聞熱點
疑難解答
圖片精選