通过解析原始帖子数据获得wordpress帖子中的第一个图像,更好的选择?

时间:2013-01-18 02:45:08

标签: php html wordpress

我有一个网站需要显示特定类别中任何给定帖子的第一张图片。我有它工作,并在下面添加了代码。我的问题是,有更好的方法吗?这看起来非常糟糕。

我正在解析src=""之间首次出现的帖子数据。我错过了任何问题吗? Wordpress有更好的方法来内置吗?

function extractStringFromString($string, $start, $end) {
//Finds the first string between $start and $end. 

    $startPos = strpos($string,$start);

    $stringEndTagPos = strpos($string,$end,$startPos);

    $stringBetween = substr($string,$startPos+strlen($start),$stringEndTagPos-$startPos-strlen($start));

    if (strlen($stringBetween) != 0 && $startPos!= '') {
        return $stringBetween;
    }
    else {
        return false;
    }



}
function getfirstimage($post){
//Returns url of first image located in post data
global $wpdb;

$sqlquery = "SELECT post_content FROM  `wp_posts` WHERE  `ID` = $post LIMIT 0 , 1";
$result = $wpdb->get_results( $sqlquery );
$result = $result[0];
$postcontent = $result->post_content;

if ($result){
    return extractStringFromString($postcontent, 'src="', '" ');
}

else return 0;

}

3 个答案:

答案 0 :(得分:1)

第3个选项:使用Dom Parser

<?php
while(have_posts()) : the_post();
    $dom = new DOMDocument();
    $dom->loadHTML(get_the_content());
    $images = $dom->getElementsByTagName('img');
    $src = $images->item(0)->getAttribute('src');
    echo 'Src: '.$src.'<br/>';
    echo 'First Image: '.$images->item(0)->saveHTML();
    echo 'Image HTML: '.htmlentities($images->item(0)->saveHTML());
endwhile;
?>

这应该让你开始朝着正确的方向前进。正则表达式不会考虑格式错误的HTML,也不是Post HTML中的所有图像都必然是附件。

答案 1 :(得分:0)

使用此功能,如果您在The Loop内,则可以使用 get_the_ID()替换 $ post-&gt; ID

<?php //GET THE FIRST IMAGE
    $args = array(
        'order'          => 'ASC',
        'orderby'        => 'menu_order',
        'post_type'      => 'attachment',
        'post_parent'    => $post->ID,
        'post_mime_type' => 'image',
        'post_status'    => null,
        'numberposts'    => 1,
    );
    $attachments = get_posts($args);
    if ($attachments) {
        foreach ($attachments as $attachment) {
            echo wp_get_attachment_link($attachment->ID, 'thumbnail', false, false);
        }
    } 
?>

来源:WordPress Support Forums

答案 2 :(得分:0)

有一个非常好的插件叫做Get The Image。 http://wordpress.org/extend/plugins/get-the-image/

<?php if ( function_exists( 'get_the_image' ) ) get_the_image(); ?>

打电话

功能:

1) Looks for an image by custom field (one of your choosing).
2) If no image is added by custom field, check for an image using
   the_post_thumbnail() (WordPress featured image).
3) If no image is found, it grabs an image attached to your post.
4) If no image is attached, it can extract an image from your post content
   (off by default).
5) If no image is found at this point, it will default to an image you set
   (not set by default).