WordPress的10个杀手级Hack技巧 4 转

[复制链接]
查看: 1101   回复: 0
发表于 2009-1-10 10:31:59 | 显示全部楼层 |阅读模式
4.自动获取文章图像

问题:使用自定义字段来显示和日志相关的图像固然很好,但是许多用户想直接检索并使用文章本身嵌入的图像。

解决方案: 至今为止,还没有这样的插件。值得庆幸的是,以下循环将帮我们解决这一问题:它会搜索文章内容的图像并把它们显示出来
把以下代码粘贴到主题文件任意位置:
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<?php
$szPostContent = $post->post_content;
$szSearchPattern = '~<img [^\>]*\ />~';
// Run preg_match_all to grab all the images and save the results in $aPics
preg_match_all( $szSearchPattern, $szPostContent, $aPics );
// Check to see if we have at least 1 image
$iNumberOfPics = count($aPics[0]);
if ( $iNumberOfPics > 0 ) {
// Now here you would do whatever you need to do with the images
// For this example the images are just displayed
for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
echo $aPics[0][$i];
};
};
endwhile;
endif;
?>

代码说明:以上代码实际上包含了一个WordPress循环。使用PHP和正则表达式的唯一区别就是前者会自动搜索文章内容中的图像而不是仅仅显示文章。一旦发现图像,系统就会显示。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则