4.自動獲取文章圖像
5 W4 a J L) {- W( T* S3 i1 T7 A, _" c$ C# h' q
問題:使用自定義字段來顯示和日誌相關的圖像固然很好,但是許多用戶想直接檢索並使用文章本身嵌入的圖像。: ~$ P0 c! m2 i1 Z# f2 E8 U t
4 _5 }; n" g, j# r解決方案: 至今為止,還沒有這樣的插件。值得慶幸的是,以下循環將幫我們解決這一問題:它會搜索文章內容的圖像並把它們顯示出來
/ p$ |/ y/ O. d; l! g/ V把以下代碼粘貼到主題文件任意位置:
- L3 h) y2 ?3 N. `; ^<?php if (have_posts()) : ?>
" r$ r3 q! f7 e8 d<?php while (have_posts()) : the_post(); ?>- y4 d2 e, \5 D# p
<?php
3 a+ r* S; I- |$ H& U" u) ]$szPostContent = $post->post_content;
* ~' `! l/ A* F; \1 u+ E$szSearchPattern = '~<img [^\>]*\ />~';
W" l {* W7 M( X- T// Run preg_match_all to grab all the images and save the results in $aPics
/ g$ ?# Z4 M9 E/ B" G4 Mpreg_match_all( $szSearchPattern, $szPostContent, $aPics );
8 ?" @; i$ }5 A// Check to see if we have at least 1 image
) _1 `) }/ S% Q: j' z$iNumberOfPics = count($aPics[0]);
% u3 Z3 u/ X$ _# eif ( $iNumberOfPics > 0 ) {) U L4 _- D& R7 [
// Now here you would do whatever you need to do with the images3 u! H6 D) h% F3 R1 d; ]4 _$ Q; ?
// For this example the images are just displayed
+ l8 d9 l1 B% d6 Sfor ( $i=0; $i < $iNumberOfPics ; $i++ ) {
$ }3 P4 Z. E/ J e+ A3 q2 W: p& f; Z' Hecho $aPics[0][$i];- n) Z+ Z+ G4 k' T$ R" z6 _
};
9 l w! Z7 ~5 X( m" |' o3 ~};
, ~& S! x @) @$ bendwhile;+ v1 Y$ h) d) U s% C/ }3 Z
endif;( p! J! }, E+ H; p1 c/ V( i
?>
( \3 z9 ]# i3 `
( m/ A8 d( \4 }9 j代碼說明:以上代碼實際上包含了一個WordPress循環。使用PHP和正則表達式的唯一區別就是前者會自動搜索文章內容中的圖像而不是僅僅顯示文章。一旦發現圖像,系統就會顯示。 |
|