Mar*_*c P 0 wordpress loops image function
在我的主页上,我正在尝试输出每个帖子的第一张图片,并且我能够在我的functions.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;
}
Run Code Online (Sandbox Code Playgroud)
然后我在我的循环中调用它,如下所示:
<img src=”<?php catch_that_image(); ?>” />
Run Code Online (Sandbox Code Playgroud)
这种方法的问题是,如果我在同一篇文章中放置一个库,它将无法工作.我很困惑,因为帖子的输出仍然呈现img标记,我的假设是catch_that_image()应该阻止该标记?我的想法不正确吗?有没有更好的方法来处理这个?
使用WordPress短标签将图库放置在您的帖子内.当应用用于转换短标签的过滤器时,短标签将转换为HTML图像标签.
以下可能有效,但我不确定:
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$transformed_content = apply_filters('the_content',$post->post_content);
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $transformed_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
Run Code Online (Sandbox Code Playgroud)
请告诉我这是否有用或是否指向正确的方向!
法典链接:
http://codex.wordpress.org/Gallery_Shortcode
http://codex.wordpress.org/Function_Reference/apply_filters
http://codex.wordpress.org/Function_Reference/do_shortcode
| 归档时间: |
|
| 查看次数: |
2797 次 |
| 最近记录: |