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

3 番目のオプション: 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 を考慮しません。また、投稿 HTML のすべての画像が必ずしも添付ファイルであるとは限りません。

于 2013-01-18T04:25:19.010 に答える
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 に答える
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 に答える