抓取WordPress帖子的图像并显示它?

时间:2011-01-21 16:46:50

标签: php wordpress

有没有办法获取帖子的第一张图片并将其显示为主页上帖子本身的缩略图链接?我似乎无法弄明白。不想使用特色图像功能。有解决方法吗?任何帮助将不胜感激。


我是否可以使用以下代码来实现我想要的效果?我似乎不能指定帖子ID,但也许我错了?

http://www.wordimpressed.com/wordpress/get-the-first-image-from-a-post-and-display-it/

我主要担心的是抓住几个帖子并能够在首页/主页上显示它们。这可能吗?

2 个答案:

答案 0 :(得分:0)

我在循环中使用了类似的代码。它应该适合你!

        $content = $post->post_content;
    $content = preg_replace('/\[.*\]/', '', $content);
    $image = '';
    $x = stripos($content, '<img');
    if ($x !== false) {
        $x = stripos($content, 'src="', $x);
        if ($x !== false) {
            $x += 5;
            $y = strpos($content, '"', $x);
            $image = substr($content, $x, $y-$x);
        }
    }

它对我来说很好,所以如果你有问题请告诉我。 ;)

答案 1 :(得分:0)

你可以通过两种方式实现:

function post_photo_count_attachments( $post_id ) {

    $attachments = get_children(
        array( 'post_parent' => $post_id ) 
    );

    return( $attachments[0] );

}

或者通过Query / XPath方法:

function post_photo_count_xpath( $post_id ) {
    global $wpdb;

    $post_id_safe = intval( $post_id );

    $html = $wpdb->get_row(
        "select * from {$wpdb->posts} where ID={$post_id_safe} limit 1"
    );

    $doc = new DOMDocument();
    @$doc->loadHTML( $html->post_content );
    $path = new DOMXpath( $doc );
    $images = $path->query( "//img" );

    return( $images->item(0)->getAttribute('src') );
}

print_r()这些返回以获取更多详细信息。