Php 从相关帖子捕获第一张图片(wp)
我写这段代码是为了显示相关帖子中的缩略图。如果相关帖子没有缩略图,则应显示其内容的第一个图片:Php 从相关帖子捕获第一张图片(wp),php,post,wordpress,thumbnails,Php,Post,Wordpress,Thumbnails,我写这段代码是为了显示相关帖子中的缩略图。如果相关帖子没有缩略图,则应显示其内容的第一个图片: $output .= "<a href=\"".get_permalink($related_post->ID)."\">"; if(get_the_post_thumbnail($related_post->ID)) { $output .= get_the_post_thumbnail($related_post-&
$output .= "<a href=\"".get_permalink($related_post->ID)."\">";
if(get_the_post_thumbnail($related_post->ID)) {
$output .= get_the_post_thumbnail($related_post->ID, $options['thumbnail_size']);
} else {
$output .= catch_image( $related_post->ID );
}
$output .= "</a>";
$output.=”;
在function.php中,我有一个函数:
function catch_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)) {
$first_img = "url for noimage.jpg";
}
return $first_img;
}
函数catch_image(){
全球$员额,$员额;
$first_img='';
ob_start();
ob_end_clean();
$output=preg_match_all('//i',$post->post_content,$matches);
$first_img=$matches[1][0];
如果(空($first_img)){
$first_img=“noimage.jpg的url”;
}
返回$first\u img;
}
但这只是这篇文章的第一张图片,而不是相关文章。我如何获取我需要的内容 尝试使用此功能:
function catch_image($post_id) {
$first_img = '';
ob_start();
ob_end_clean();
$related_post = get_post($post_id);
$content = $related_post->post_content;
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
$first_img = $matches[1][0];
if(empty($first_img)) {
$first_img = "url for noimage.jpg";
}
return $first_img;
}
函数捕捉图像($post\u id){
$first_img='';
ob_start();
ob_end_clean();
$related\u post=get\u post($post\u id);
$content=$related\u post->post\u content;
$output=preg_match_all('//i',$content,$matches);
$first_img=$matches[1][0];
如果(空($first_img)){
$first_img=“noimage.jpg的url”;
}
返回$first\u img;
}