4.自動獲取文章圖像% g' n3 W w5 ]8 }1 N- k
) E$ u' `% T" ] ~9 L! ]問題:使用自定義字段來顯示和日誌相關的圖像固然很好,但是許多用戶想直接檢索並使用文章本身嵌入的圖像。' W6 m" k C, H1 q8 K! V: b
u! i5 H. D& P3 y解決方案: 至今為止,還沒有這樣的插件。值得慶幸的是,以下循環將幫我們解決這一問題:它會搜索文章內容的圖像並把它們顯示出來
* j+ {- |3 a# T' B) [0 f把以下代碼粘貼到主題文件任意位置:
" n! W2 x5 {- T, F5 a) j<?php if (have_posts()) : ?>% u( F/ w; L u U
<?php while (have_posts()) : the_post(); ?>
: T3 }0 i p {3 P% p! b<?php& o) v, Q0 W% N2 c! r0 F8 a" F
$szPostContent = $post->post_content;) `1 [) d1 Z' m& m
$szSearchPattern = '~<img [^\>]*\ />~';
* E, h- I( b$ n; \: \' B// Run preg_match_all to grab all the images and save the results in $aPics
- E* e8 J: o- |preg_match_all( $szSearchPattern, $szPostContent, $aPics );, I8 s# i: r9 K2 ]
// Check to see if we have at least 1 image
, g# {6 {" n3 ~% T0 X$iNumberOfPics = count($aPics[0]);- E3 Q% A- ^5 @3 \7 _& _- H
if ( $iNumberOfPics > 0 ) {
, i0 |( n4 T. Q// Now here you would do whatever you need to do with the images
+ R, v4 p- x7 N$ Q9 z8 i// For this example the images are just displayed
# E& }! h' s; S. H' Xfor ( $i=0; $i < $iNumberOfPics ; $i++ ) {, p( F2 I' k+ U. N$ G# ?! L
echo $aPics[0][$i];7 P5 V2 z. v2 O
};
' K6 u7 @; I( ]5 E: B; L% n4 _) U};
* q/ k/ b+ D$ h, Tendwhile;/ k2 T0 T7 Q: G' U6 n1 ^. e* r
endif;6 m" P3 T* K9 d8 N ^5 E2 X7 C
?>; h6 ~0 k+ o0 |6 `4 e
1 l. N0 T- {5 [: Y" r/ T' R. b
代碼說明:以上代碼實際上包含了一個WordPress循環。使用PHP和正則表達式的唯一區別就是前者會自動搜索文章內容中的圖像而不是僅僅顯示文章。一旦發現圖像,系統就會顯示。 |
|