1

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

我正在解析帖子数据中首先出现在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;

}

4

3 回答 3

1

第三个选项:使用Dom 解析器

<?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 中的所有图像都必须是附件。

于 2013-01-18T04:25:19.010 回答
0

使用它,如果您在The Loop中,则可能将$post->ID替换为get_the_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 支持论坛

于 2013-01-18T03:06:36.987 回答
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).
于 2013-01-18T05:39:17.983 回答