WordPress技巧:自动显示文章第一张图片
在修改主题的时候,我们可能需要WordPress自动获取文章第一张图片,在博客吧看到了相关的实现方法,记录一下,估计以后也用得到。
在当前使用的主题模板的functions.php文件<?php和?>之前添加以下代码
function catch_that_image() { global $post, $posts; $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); $first_img = $matches [1] [0]; if(empty($first_img)){ //Defines a default image $first_img = "/images/default.jpg"; } return $first_img; } |
在当前主题模板的index.php文件的内容代码前或后添加以下代码
<?php echo catch_that_image() ?> |
当然了,要限制显示图片的效果(比如大小、边框),就需要你使用css设置了。
分享到: