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?
1 Answer
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.org/Function_Reference/get_attachment_link and https://codex.wordpress.org/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.
-
-
The WordPress terminology is a bit confusing. The
get_posts()
function should really be calledget_content_ids()
. There's a single set of ids for all the content -- posts, pages, attachments, etc... Feb 13, 2019 at 3:14 -
... In this case, the ids returned will all be of attachments, because the
'post_type'
argument (which really should be called'content_type'
) is'attachment'
. Anyway, might be preferable to callget_children()
(which I think is essentially a wrapper aroundget_posts()
), then callwp_get_attachment_image()
to actually generate theimg
tag. The latter will also generate html that references an image of the desired size, if a pre-generated image exists. Feb 13, 2019 at 3:14 -
...let me know if it's still unclear, if you need sample code, or if your attempts don't work as expected or desired. Feb 13, 2019 at 3:18