4.自動獲取文章圖像
" O9 ~# |6 p7 d5 |6 r" j* j" t7 _* }
問題:使用自定義字段來顯示和日誌相關的圖像固然很好,但是許多用戶想直接檢索並使用文章本身嵌入的圖像。/ d% }$ ?0 `6 j" H6 v
2 u1 _' n3 M7 C# h4 i
解決方案: 至今為止,還沒有這樣的插件。值得慶幸的是,以下循環將幫我們解決這一問題:它會搜索文章內容的圖像並把它們顯示出來
7 r# S( `# }5 ?0 G把以下代碼粘貼到主題文件任意位置:
6 y' C' C1 }, N- t<?php if (have_posts()) : ?>8 }4 R, h% Q4 Y! w. z$ w
<?php while (have_posts()) : the_post(); ?>. `, Y7 _( q% F$ i7 A& q
<?php
6 d% }, L# A) L1 A4 p$szPostContent = $post->post_content;
" ~: F$ `7 m2 P" g" v6 \* Z9 }6 y$szSearchPattern = '~<img [^\>]*\ />~';; E: O3 v2 L n: q7 N
// Run preg_match_all to grab all the images and save the results in $aPics8 B1 B9 y T. A; U
preg_match_all( $szSearchPattern, $szPostContent, $aPics );
2 j- W' O" L6 E4 W// Check to see if we have at least 1 image
0 S: ?1 c4 E0 r$iNumberOfPics = count($aPics[0]);
; b7 g, G2 H& d% C% Zif ( $iNumberOfPics > 0 ) {
2 U; o* b' `. H. b* g1 l! J// Now here you would do whatever you need to do with the images9 S: K7 |0 p! K4 _
// For this example the images are just displayed" l, G7 q* h# O+ A) K6 u" O P
for ( $i=0; $i < $iNumberOfPics ; $i++ ) {* N: Z3 [( x+ @" `3 q$ F+ }
echo $aPics[0][$i];( r% Q, k3 I e: ?9 y' C. L
};
9 B2 N$ f! N4 i/ R8 Q% c}; P6 H. Q9 Q( l! E/ |
endwhile;
* E3 q+ e& F6 |endif;4 P7 @4 J! u2 h0 `7 R
?>
t4 K+ Y2 [, ^0 S) \
# H) ?2 T7 o# J: G% G! @代碼說明:以上代碼實際上包含了一個WordPress循環。使用PHP和正則表達式的唯一區別就是前者會自動搜索文章內容中的圖像而不是僅僅顯示文章。一旦發現圖像,系統就會顯示。 |
|