Reputation: 2124
I created some custom post types and what i intend to do now is insert an image in the post and get its url on server so that i can use it as a background for some div. Now i saw the function get_attachment_uri($id); but i dont understand how i can get the id of that attachment in the loop?
Now what i am doing is manually uploading the image in the images folder and then use a custom field to store its name, so that i can use it like this -
<div class="ch-info-front" style="background-image: url(<?php bloginfo('template_url'); ?>/images/<?php get_post_meta($post->ID, 'image_no', true); ?>.png);"></div>
Now there has to be some other nicer way of doing it but i am not well aware of that, can anyone help?
Upvotes: 0
Views: 2697
Reputation: 578
You can call the first image attached to a post using get_children
and then getting it's URL and outputting it in your code there. I've written this quickly, it's not tested but I'm fairly confident it would work.
<?php
$args = array(
'post_parent' => get_the_ID(),
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => 1,
'order' => 'ASC'
);
$attachments = get_children( $args )
foreach ( $attachments as $attachment_id => $attachment ) {
$image = wp_get_attachment_link($attachment_id);
break;
}
echo $image; // this is the image URL
?>
That will automatically get the first image and give you the URL for your theme. You might want to add in an if statement as well in case there are no images.
Upvotes: 0