Reputation:
I'm trying to convert a static HTML site into a WordPress theme. At the moment, there is the following (static) code:
<div class="postwrap">
<div class="first-col">
<!-- Post Description -->
<h1>Post Title</h1>
<p>Post description. At essimag nimilib errorum fuga. Harunt faci aut elitatur.</p>
</div>
<div class="second-col">
<!-- Post Images -->
<img src="images/placeholder.png" alt="This is a photo">
</div>
</div>
As you can see, all the content in first-col
is text-based. All the content in second-col
are images, and WordPress simply uses <?php get_content(); ?>
grab this content.
Is there a way I can sort images submitted into a separate div, such as second-col
? I'm aware this can be done with jQuery, but I'm wondering if there's a method with PHP or WordPress.
Upvotes: 0
Views: 1129
Reputation: 120
Yes, you can display any images that have been uploaded/attached to a post/page by using the following code.
<div class="second-col">
<?php
// Get all images uploaded/attached to this post/page.
if (
$images = get_posts(
array(
'post_parent' => get_the_ID(),
'post_type' => 'attachment',
'post_mime_type' => 'image',
'orderby' => 'menu_order',
'order' => 'ASC'
)
)
) :
// Loop through the results and display each full-size image.
foreach( $images as $image ) :
echo wp_get_attachment_image( $image->ID, 'full' );
endforeach;
endif;
?>
</div>
get_posts()
is a WordPress function that returns an array of posts based on the parameters we pass to it. We then loop through that array and call the wp_get_attachment_image()
function on each value in it. wp_get_attachment_image()
is another WordPress function that returns an HTML image element.
In order to display the images only in the second column, do NOT insert them into the post/page. Simply upload them from the post/page edit screen then close the modal window and update the post/page. You could also upload images from the media library and attach them to the post/page you want.
Upvotes: 4