在wordpress顯示文章的時候,如果文章形式是圖片的文章,需要把里面的圖片部分的代碼進行修改和替換,如把以下代碼:
- <img src="/wp-content/uploads/2014/02/hbzy1.gif" alt="hbzy"
- width="60" height="60" class="alignnone size-full wp-image-2100" />
輸出顯示的時候替換成如下代碼:
- <div class="gif-box">
- <img src="/wp-content/uploads/2014/02/hbzy1.jpg!static"
- _src="/wp-content/uploads/2014/02/hbzy1.jpg!static"
- class="alignnone size-full wp-image-2100"
- tsrc="/wp-content/uploads/2014/02/hbzy1.jpg" width="60" height="60" />
- <div class="gif-loading-box">
- <i class="gif-loading" style="display:none;"></i>
- <i class="gif-play"></i>
- </div>
- </div>
這里是為了動態gif圖片默認的時候不播放,點擊才播放,這個時候需要用到preg_match和正則表達式匹配圖片代碼,并用str_replace進行字符串的替換和修改,代碼如下:
- function gif_content($content) {
- $content = get_the_content ();
- $img_html = preg_match ( '/(<img[^>]+>)/i', $content, $maches ); //獲取img圖片的html,如:<img src=".." class=".." width=""> //www.111cn.net
- $img_html = $maches [0];
- $img_width = preg_match ( '/width="[0-9]+"/i', $img_html, $maches ); //獲取圖片寬度,如:width="32"
- $img_width = str_replace('=', ':', $maches[0]);
- $img_width = str_replace('"', '', $img_width);
- $img_width = $img_width.'px'; //替換成width:32px
- $img_height = preg_match ( '/height="[0-9]+"/i', $img_html, $maches );
- $img_height = str_replace('=', ':', $maches[0]);
- $img_height = str_replace('"', '', $img_height);
- $img_height = $img_height.'px';
- $img_name = preg_match ( '!http://.+.(?:jpe?g|png|gif)!Ui', $img_html, $maches );
- $img_name = $maches [0];
- $img_html2 = str_replace ( 'src="' . $img_name . '"', 'src="' . $img_name . '!static" _src="' . $img_name . '!static' . '" tsrc="' . $img_name . '"', $img_html );
- $img_html2 = '<div class="gif-box" style="'.$img_width.';'.$img_height.'">' . $img_html2 . '<div class="gif-loading-box"><i class="gif-loading" style="display:none;"></i><i class="gif-play"></i></div></div>';//在圖片的html代碼前后加上div
- $content = str_replace ( $img_html, $img_html2, $content );
- return $content;
- }
- add_filter('the_content', 'gif_content', 10);//wordpress的鉤子函數
這里是用在wordpress的文章形式中的,當文章形式是image的時候,給這個文章形式下的圖片進行這樣的操作,另外在index.php中需要使用如下代碼:
- $format=get_post_format();
- if ('image'!=$format) {
- remove_filter('the_content', 'gif_content');
- }
- get_template_part( 'content', get_post_format() );
這里要判斷一下如果是其他文章形式就移除這個鉤子,否則所有文章形式的圖片都被進行這樣的操作,本文講的是preg_match正則提取和替換字符串,以及wordpress的文章形式.
新聞熱點
疑難解答
圖片精選