4.自動獲取文章圖像
! d4 p ]8 z0 t3 F# ]( ]
( q1 ~1 I: r8 s* x* ~/ ?/ e3 W問題:使用自定義字段來顯示和日誌相關的圖像固然很好,但是許多用戶想直接檢索並使用文章本身嵌入的圖像。
* P8 ~9 S; w5 F1 g
1 N% z# `' ~! }2 Z4 G& Q解決方案: 至今為止,還沒有這樣的插件。值得慶幸的是,以下循環將幫我們解決這一問題:它會搜索文章內容的圖像並把它們顯示出來! S: S2 K8 G) T5 e
把以下代碼粘貼到主題文件任意位置:! |5 q( R: ?& I( h
<?php if (have_posts()) : ?>: U4 {/ `) [; x( H1 ^
<?php while (have_posts()) : the_post(); ?>
) }( e: G, A R6 c+ u1 u' B6 S<?php: O. @' e7 {- n
$szPostContent = $post->post_content;
0 E8 R5 m2 E6 B& a$szSearchPattern = '~<img [^\>]*\ />~';( L7 |/ N) [' ?; z; G7 I* L
// Run preg_match_all to grab all the images and save the results in $aPics
1 S$ S' Q8 y; H) ]$ Y: u: Epreg_match_all( $szSearchPattern, $szPostContent, $aPics );, l; ~ \- }$ V
// Check to see if we have at least 1 image
* s7 e8 m' E2 a9 X; v$iNumberOfPics = count($aPics[0]);
) _" v; l6 q q/ h6 N7 p' m9 lif ( $iNumberOfPics > 0 ) {* F3 Q" P# {. V U. u3 p
// Now here you would do whatever you need to do with the images) I5 y$ V' l1 F( \+ i* H
// For this example the images are just displayed0 l/ l. y2 I0 p2 P5 f
for ( $i=0; $i < $iNumberOfPics ; $i++ ) {- {2 l$ X7 ~+ M! H
echo $aPics[0][$i];
, L' B3 k/ z$ }, w+ w& n, Q* j};
9 R+ `( V- \7 L2 v};9 j# S5 N# H8 i% y
endwhile;
k; V9 l( L$ `1 Kendif;2 R3 m3 r8 K! Z! t
?>; w' c+ [% |& b6 v3 K2 @
1 }% u, m ~% o9 e: I* e C/ A
代碼說明:以上代碼實際上包含了一個WordPress循環。使用PHP和正則表達式的唯一區別就是前者會自動搜索文章內容中的圖像而不是僅僅顯示文章。一旦發現圖像,系統就會顯示。 |
|