4.自動獲取文章圖像
9 x9 _5 M O6 Z2 d. c5 Q
6 a- L& _5 {/ K# F3 Z2 Z3 H問題:使用自定義字段來顯示和日誌相關的圖像固然很好,但是許多用戶想直接檢索並使用文章本身嵌入的圖像。- e6 @3 F4 E+ w% M/ k
) G* O3 M, D+ ^( i, o f% b解決方案: 至今為止,還沒有這樣的插件。值得慶幸的是,以下循環將幫我們解決這一問題:它會搜索文章內容的圖像並把它們顯示出來
8 O/ w1 \( k9 H. G, D( }把以下代碼粘貼到主題文件任意位置:) O: O( u0 `3 K* w6 A
<?php if (have_posts()) : ?>. N! i* [ T1 L2 H: i/ ]1 b
<?php while (have_posts()) : the_post(); ?># d3 h( ~: L0 y- a7 ]
<?php
# ?% o% X" Z ]4 p' ^: d$szPostContent = $post->post_content;
% Q7 G' E% B3 [$szSearchPattern = '~<img [^\>]*\ />~';9 \, [& g2 A: i- g; L2 v$ n* R( X/ `
// Run preg_match_all to grab all the images and save the results in $aPics
4 f( C- o, H( }preg_match_all( $szSearchPattern, $szPostContent, $aPics );
7 K% O G! C! [' |2 }8 R- Q2 W) n: Q// Check to see if we have at least 1 image: ?2 M9 W8 s8 u0 m
$iNumberOfPics = count($aPics[0]);
) e) y% j( K( h% G9 ?, rif ( $iNumberOfPics > 0 ) {
5 @: [& I, v& W* m& U// Now here you would do whatever you need to do with the images
: L/ C+ G# u5 b) O- x% V// For this example the images are just displayed
2 o1 Z" M2 b2 \for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
8 [; F# e0 ]& N& V4 e0 aecho $aPics[0][$i];
( o7 v& w2 u2 P6 \4 I};
/ T- R6 Z$ b' r3 _: O& U3 R' v};; V5 {" [& O2 E; {. w
endwhile;
# c+ M: S5 L7 d1 q6 z- h K: m* Lendif;
4 N4 V* Q& T2 A; X. t: p0 j?>
/ v% h. `) U9 H7 O
6 x& @1 A4 w: \7 ^1 k9 a4 ?代碼說明:以上代碼實際上包含了一個WordPress循環。使用PHP和正則表達式的唯一區別就是前者會自動搜索文章內容中的圖像而不是僅僅顯示文章。一旦發現圖像,系統就會顯示。 |
|