【问题标题】:Catch the first image from post_meta instead of post_content从 post_meta 而不是 post_content 捕获第一张图片
【发布时间】: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 吗?

【问题讨论】:

    标签: wordpress custom-fields


    【解决方案1】:

    我知道您有不止一张图像存储为自定义字段(发布元),名称为“my_custom_field”,对吧?

    $photo_gallery = get_post_meta($post->ID,'my_custom_field', true);
    

    true 表示返回最后输入的值。如果你把它改成false,你会得到所有的图片,这样你就可以得到第一个:

    $photo_gallery = get_post_meta($post->ID,'my_custom_field', false);
    $first_photo = $photo_gallery[0];
    

    【讨论】:

    • 没有这个自定义字段,我们可以说我将其用作内容,因为 the_content();用于描述,因此我不想从帖子内容中捕获第一张图片,而是想在此自定义字段部分中搜索它
    • 刚刚更新了我的第一篇文章,我已经按照你告诉我的方式尝试过,但没有成功:(
    【解决方案2】:

    您是否尝试使用$photo_gallery 进行更改, 在

    $output = preg_match_all('https://yourdomain.com/&lt;img.+src=[\'"]([^\'"]+)[\'"].*&gt;/i', $photo_gallery, $matches);

    你可以调试print_r($photo_gallery);,看看你的$photo_gallery是不是你想要的内容。

    【讨论】:

    • Simeon $photo_gallery 只是一个自定义字段,我将其用作自定义内容,因此 the_content();用于我的主题中的描述,我想从这个自定义字段中获取第一张图片,而不是我尝试过你的解释但没有用的帖子内容。谢谢你的回复
    • 我在 preg_match_all 中错了,因为我的图片不在 img 标签中,而是在自定义内容中作为 url
    • 您需要 preg_match 代替 URL。 stackoverflow.com/questions/2762260/….
    • 是的,但是有多个不同格式的网址我只需要 jpg 和 png 格式
    • 但问题不存在,因为它始终显示默认图像我不确定它是否在自定义字段中搜索,我尝试了您在上面链接中告诉我的相同预匹配
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 2011-12-28
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多