【问题标题】:Wordpress get the first attached image on the postWordpress 获取帖子上的第一个附加图片
【发布时间】:2013-06-05 18:50:53
【问题描述】:

今天我一直在尝试使用以下代码在 wordpress 中显示最受欢迎的帖子:

http://pastebin.com/TjJTiiTZ

效果很好,但它不允许我抓取帖子上的第一个附加图片。我需要这样做才能从保存图像的几个自定义字段中的任何一个中获取图像。

我尝试使用以下代码(实际上适用于另一个自定义)来获取帖子上的第一个附加图像,但我无法使其工作。

$p = array(
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'numberposts' => 1,
    'order' => 'ASC',
    'orderby' => 'menu_order ID',
    'post_status' => null,
    'post_parent' => $post->ID
);

$thumb = get_posts($p);
    if ($thumb) {
    $imgsrc = wp_get_attachment_image_src($thumb[0]->ID, 'thumbnail');
    $img = $imgsrc[0];
    }

有什么方法可以实现吗??

【问题讨论】:

  • 尝试将$attachments[0]->ID更改为$thumb[0]->ID
  • 调试一下$thumb的内容是什么?

标签: php wordpress


【解决方案1】:

您可以使用此代码获取帖子的第一个附件图片:

$catposts = get_posts('category='.$category_id."&order=DESC&numberposts=".$NUMBEROFPOSTS);
function catch_that_image($_catposts)
{
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $_catposts->post_content, $matches);
$first_img = $matches[1][0];
return $first_img;
}

$j=0;
foreach ($catposts as $item) :
    $get_contents = $item->post_content;
    $regex_pattern = "/<a href=\"(.*)\">(.*)<\/a>/";
        $output = preg_match_all($regex_pattern,$item->post_content, $matches);
    echo '<img src="'.catch_that_image($catposts[$j]).'" alt="" border="0px" />';
    $j++;
endforeach;

其中 $category_id 是特定类别 id 。假设如果您有一个类别 id = 26,那么所有 26 个类别的帖子都会显示在 foreach 循环中。

在相关帖子上显示您在帖子中输入的第一张图片。

谢谢。

【讨论】:

  • 它工作得很好,但是我想要完成的是从帖子元的任何字段中获取帖子。您的代码只会搜索帖子内容中插入的任何图像。我需要搜索附加到帖子的任何图像(在描述中或在特色图像、自定义字段等中)
猜你喜欢
  • 2011-12-28
  • 2015-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多