Grabbing A WordPress Post's Image and Displaying it?
Is there a way to grab a post's first image and have it displayed as a thumbnail link to the post itself on the homepage? I can't seem to figure it out. Prefer not to use the featured image function. Is there a workaround? Any help would be much appreciated.
Would I be able to use the foll开发者_开发百科owing code to acheive what I want? It doesn't seem like I can specify a post ID, but maybe i'm wrong?
http://www.wordimpressed.com/wordpress/get-the-first-image-from-a-post-and-display-it/
My main concern is grabbing a few posts and being able to display them on the frontpage/homepage. Is that possible?
You could do it through two ways:
function post_photo_count_attachments( $post_id ) {
$attachments = get_children(
array( 'post_parent' => $post_id )
);
return( $attachments[0] );
}
Or by Query/XPath method:
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() these returns for more detailed information.
I've a code similar working in my web in the loop. It should work fine for you!
$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);
}
}
It works fine for me, so if you've problems please tell me. ;)
精彩评论