过期域名预定抢注

 找回密碼
 免费注册

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

[複製鏈接]
發表於 2009-1-10 10:31:59 | 顯示全部樓層 |閱讀模式
4.自動獲取文章圖像
5 W4 a  J  L) {- W( T* S3 i1 T7 A, _" c$ C# h' q
問題:使用自定義字段來顯示和日誌相關的圖像固然很好,但是許多用戶想直接檢索並使用文章本身嵌入的圖像。: ~$ P0 c! m2 i1 Z# f2 E8 U  t

4 _5 }; n" g, j# r解決方案: 至今為止,還沒有這樣的插件。值得慶幸的是,以下循環將幫我們解決這一問題:它會搜索文章內容的圖像並把它們顯示出來
/ p$ |/ y/ O. d; l! g/ V把以下代碼粘貼到主題文件任意位置:
- L3 h) y2 ?3 N. `; ^<?php if (have_posts()) : ?>
" r$ r3 q! f7 e8 d<?php while (have_posts()) : the_post(); ?>- y4 d2 e, \5 D# p
<?php
3 a+ r* S; I- |$ H& U" u) ]$szPostContent = $post->post_content;
* ~' `! l/ A* F; \1 u+ E$szSearchPattern = '~<img [^\>]*\ />~';
  W" l  {* W7 M( X- T// Run preg_match_all to grab all the images and save the results in $aPics
/ g$ ?# Z4 M9 E/ B" G4 Mpreg_match_all( $szSearchPattern, $szPostContent, $aPics );
8 ?" @; i$ }5 A// Check to see if we have at least 1 image
) _1 `) }/ S% Q: j' z$iNumberOfPics = count($aPics[0]);
% u3 Z3 u/ X$ _# eif ( $iNumberOfPics > 0 ) {) U  L4 _- D& R7 [
// Now here you would do whatever you need to do with the images3 u! H6 D) h% F3 R1 d; ]4 _$ Q; ?
// For this example the images are just displayed
+ l8 d9 l1 B% d6 Sfor ( $i=0; $i < $iNumberOfPics ; $i++ ) {
$ }3 P4 Z. E/ J  e+ A3 q2 W: p& f; Z' Hecho $aPics[0][$i];- n) Z+ Z+ G4 k' T$ R" z6 _
};
9 l  w! Z7 ~5 X( m" |' o3 ~};
, ~& S! x  @) @$ bendwhile;+ v1 Y$ h) d) U  s% C/ }3 Z
endif;( p! J! }, E+ H; p1 c/ V( i
?>
( \3 z9 ]# i3 `
( m/ A8 d( \4 }9 j代碼說明:以上代碼實際上包含了一個WordPress循環。使用PHP和正則表達式的唯一區別就是前者會自動搜索文章內容中的圖像而不是僅僅顯示文章。一旦發現圖像,系統就會顯示。
您需要登錄後才可以回帖 登錄 | 免费注册

本版積分規則

过期高净值品牌域名预定抢注

點基

GMT+8, 2026-7-12 12:52

By DZ X3.5

小黑屋

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