过期域名预定抢注

 找回密碼
 免费注册

WordPress的10個殺手級Hack技巧 4 轉

[複製鏈接]
發表於 2009-1-10 10:31:59 | 顯示全部樓層 |閱讀模式
4.自動獲取文章圖像
' P/ T8 x* q: V2 }
4 ?' o* M! V, o( p+ g問題:使用自定義字段來顯示和日誌相關的圖像固然很好,但是許多用戶想直接檢索並使用文章本身嵌入的圖像。
& H1 ?& k0 w- Y2 v0 B- y/ U3 b9 G/ \! n0 `3 ~
解決方案: 至今為止,還沒有這樣的插件。值得慶幸的是,以下循環將幫我們解決這一問題:它會搜索文章內容的圖像並把它們顯示出來
( g8 S5 p2 J6 o. n* U7 A! p* G把以下代碼粘貼到主題文件任意位置:
8 j% |% R  ?! a<?php if (have_posts()) : ?>
8 P% D& |* N# @$ f; Z<?php while (have_posts()) : the_post(); ?>
. P, z5 k0 E, V" y( ~' W<?php
) K$ ~% M' ~. P2 |$szPostContent = $post->post_content;% z3 Q' X; J* Q+ i' u% R
$szSearchPattern = '~<img [^\>]*\ />~';9 O" ?8 M- _" f( w
// Run preg_match_all to grab all the images and save the results in $aPics
; L) A% W7 ?  ~3 h! Hpreg_match_all( $szSearchPattern, $szPostContent, $aPics );  [: t0 K' ~' J
// Check to see if we have at least 1 image
7 Y  ?8 b1 L# d( t; k$ L4 r$iNumberOfPics = count($aPics[0]);: B! q- j. r  w: r# c* Y
if ( $iNumberOfPics > 0 ) {( m) ]. _. Z9 Q) y
// Now here you would do whatever you need to do with the images  h* {" w) l. n5 R4 F
// For this example the images are just displayed
2 L5 c' }: R1 ~. ?, p0 j" @for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
- C3 D/ l# B1 c3 xecho $aPics[0][$i];
" b2 I! C. b6 v" e8 c( r};1 ?- y6 h0 i$ Z6 y2 d$ h% j  C2 a
};0 @2 }8 E( k! t1 y
endwhile;- B/ z+ N- _' A( P! J' j6 P$ L
endif;$ B6 U9 l+ z: }0 z
?>
* r+ L. y% w6 m' ?5 B' m
# k5 P& j9 e* Z2 I% V8 G代碼說明:以上代碼實際上包含了一個WordPress循環。使用PHP和正則表達式的唯一區別就是前者會自動搜索文章內容中的圖像而不是僅僅顯示文章。一旦發現圖像,系統就會顯示。
您需要登錄後才可以回帖 登錄 | 免费注册

本版積分規則

點基跨境 數位編輯創業論壇

GMT+8, 2025-4-8 20:13

By DZ X3.5

小黑屋

快速回復 返回頂部 返回列表