Get Image Attachment in a Template
-
Hello.
How can I display any images attached to a post automatically through a template?
Also, how can I display other post attachments as well?
Please help,
-
You can use the wp_get_attachement_image function to pull all of the attached images to a post or page, but I’m not sure how to do it for other posts as well.
You can use the wp_get_attachement_image function to pull all of the attached images to a post or page, but I’m not sure how to do it for other posts as well.
How can I display them on the front page loop?
Thank you,
Andrew
I tried using this in a loop and nothing happened:
<?php echo wp_get_attachment_image( 1 ); ?>
Please help,
Andrew
I’m using this on a Page but it’s not showing the post’s images:
<?php $args= array( 'category_name' => 'Category_Name', 'paged' => $paged ); // The Query query_posts( $args ); // The Loop while ( have_posts() ) : the_post(); ?> <?php echo wp_get_attachment_image( 1 ); ?> <?php endwhile ; // Reset Post Data wp_reset_postdata () ; ?>
I am using this function in my post too.
First, paste this function on your functions.php file.
function catch_that_image() { global $post, $posts; $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); $first_img = $matches [1] [0]; if(empty($first_img)){ //Defines a default image $first_img = "/images/default.jpg"; } return $first_img; }
Once done, you can simply call the function within the loop to display the first image from the post:
<?php echo catch_that_image() ?>
Okay, thank you.
But how about if I have say 2+ images?
Thank you,
Andrew
I am using this function in my post too.
First, paste this function on your functions.php file.
function catch_that_image() {
global $post, $posts;
$first_img = ”;
ob_start();
ob_end_clean();
$output = preg_match_all(‘/<img.+src=[\'”]([^\'”]+)[\'”].*>/i’, $post->post_content, $matches);
$first_img = $matches [1] [0];if(empty($first_img)){ //Defines a default image
$first_img = “/images/default.jpg”;
}
return $first_img;
}Once done, you can simply call the function within the loop to display the first image from the post:
<?php echo catch_that_image() ?>
How can I modify it to display all images attached?
Please help.
Thank you,
Andrew
- The topic ‘Get Image Attachment in a Template’ is closed to new replies.