【发布时间】:2016-12-19 13:20:23
【问题描述】:
这里有一篇很好的文章https://css-tricks.com/snippets/wordpress/get-the-first-image-from-a-post/
但在文章中解释了如何从内容中捕捉第一张图片
$output = preg_match_all('https://cdn.css-tricks.com/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
有没有办法检查自定义字段而不是内容?
因为我不使用the_content();,但我使用
$photo_gallery = get_post_meta($post->ID,'my_custom_field', true);
echo $photo_gallery
所以我的问题是如何捕捉 $photo_gallery 中的第一张图片
以下是尝试但没有成功
function catch_that_image() {
global $post;
$first_img = '';
ob_start();
ob_end_clean();
$custom_content = get_post_meta($post->ID,'my_custom_field', false);
$output = preg_match_all('/[\w\-]+\.(jpg|png|gif|jpeg)/', $custom_content, $matches);
$first_img = $matches[1][0];
if(empty($first_img)) {
$first_img = get_template_directory_uri() . '/css/images/noimage.png';
}
return $first_img;
}
我将 preg_match 更改为 /[\w\-]+\.(jpg|png|gif|jpeg)/,因为我在自定义内容中有图像作为 url,但我看到的是 noimage.png。还是不行
我应该使用 global $wpdb 而不是 global $post 吗?
【问题讨论】: