How to add an image to a theme page template in code?

admin2025-06-03  4

So, I'm trying to do an update to a site's theme layout, and I'm not sure what exactly the right function to achieve what I want is. We have a custom theme that uses a page builder, and we can add custom layouts that are added with Advanced Custom Feeds. For greater control over layout, I'm essentially just hand coding the sections we want to add. From what I've seen in the Codex, the function get_attached_file is the closest to what I think I want, but I'm not sure how to get the attachment id from the Media gallery. What I want is some way of pulling any image in the database into a page template and not to manually set the image dimensions and avoiding hard coding image src in the template files. So...what's the better way to do this?

So, I'm trying to do an update to a site's theme layout, and I'm not sure what exactly the right function to achieve what I want is. We have a custom theme that uses a page builder, and we can add custom layouts that are added with Advanced Custom Feeds. For greater control over layout, I'm essentially just hand coding the sections we want to add. From what I've seen in the Codex, the function get_attached_file is the closest to what I think I want, but I'm not sure how to get the attachment id from the Media gallery. What I want is some way of pulling any image in the database into a page template and not to manually set the image dimensions and avoiding hard coding image src in the template files. So...what's the better way to do this?

Share Improve this question asked Feb 11, 2019 at 15:21 nizz0knizz0k 1198 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Haven't tested this, but the key is to use get_posts() with the proper arguments so as to retrieve the ids of the attachments, e.g.

   $args = array(
     'post_type' => 'attachment',
     'numberposts' => -1,
     'post_status' => null,
     'post_parent' => $post->ID
  );

  $attachments = get_posts( $args );
     if ( $attachments ) {
        foreach ( $attachments as $attachment ) {
           echo '<li>';
           the_attachment_link( $attachment->ID, true );
           echo '<p>';
           echo apply_filters( 'the_title', $attachment->post_title );
           echo '</p></li>';
          }
     }

See https://codex.wordpress/Function_Reference/get_attachment_link and https://codex.wordpress/Function_Reference/the_attachment_link.

As far as the image dimensions go, you probably want CSS for that, unless you just want to display the image as is.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748917509a314800.html

最新回复(0)