过期域名预定抢注

用戶名  找回密碼
 免费注册

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

[複製鏈接]
發表於 2009-1-10 10:31:59 | 顯示全部樓層 |閱讀模式
4.自動獲取文章圖像9 F0 A' k; `$ J0 ^4 u4 c, [8 |

' J6 S4 K/ ?8 x/ G, ]問題:使用自定義字段來顯示和日誌相關的圖像固然很好,但是許多用戶想直接檢索並使用文章本身嵌入的圖像。! w0 s' g! U1 ?8 L: V
- Q5 `% Y, P$ I2 g
解決方案: 至今為止,還沒有這樣的插件。值得慶幸的是,以下循環將幫我們解決這一問題:它會搜索文章內容的圖像並把它們顯示出來
* c0 j  X4 z5 {& S/ S  j把以下代碼粘貼到主題文件任意位置:
9 [9 m  r$ D8 V- i<?php if (have_posts()) : ?>
4 e# s3 @) x% r9 [  B1 g: G/ C<?php while (have_posts()) : the_post(); ?>
/ z. e& n2 E8 W3 n) |- |<?php
( }- g6 A/ [: R, S3 M( B5 N$szPostContent = $post->post_content;7 y% g" g5 b9 C. _0 o
$szSearchPattern = '~<img [^\>]*\ />~';
) ^7 h# _( f: e// Run preg_match_all to grab all the images and save the results in $aPics# K& i+ l1 V+ o. w: O
preg_match_all( $szSearchPattern, $szPostContent, $aPics );
9 `9 E9 ~9 E/ s: q+ v% x( F; B  A( J// Check to see if we have at least 1 image
& E. [& C, j: A9 D4 t6 R$iNumberOfPics = count($aPics[0]);
1 j; n2 J- }. U7 ^! b: [if ( $iNumberOfPics > 0 ) {: D+ g  s# O9 k
// Now here you would do whatever you need to do with the images
& J: d: Z1 x! c  t. ^// For this example the images are just displayed
  e  E3 d5 v6 [$ n: z, D  X4 Cfor ( $i=0; $i < $iNumberOfPics ; $i++ ) {
1 h1 y. J/ q- zecho $aPics[0][$i];
1 r' _' o0 }: q& J' t' D0 @};
$ a7 n7 c& R# A" E( p% U# u};
: {$ R$ c) h* C2 Tendwhile;: `  P- p. W0 n6 N; z
endif;3 @' Y0 H. O$ H
?>
1 |5 @! i3 o0 o+ l# j( n2 o
8 |5 Q  s: `! H代碼說明:以上代碼實際上包含了一個WordPress循環。使用PHP和正則表達式的唯一區別就是前者會自動搜索文章內容中的圖像而不是僅僅顯示文章。一旦發現圖像,系統就會顯示。
您需要登錄後才可以回帖 登錄 | 免费注册

本版積分規則

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

GMT+8, 2025-6-5 08:42

By DZ X3.5

小黑屋

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