WordPress: How to add images to homepage?

I’m trying to make a mod in my WordPress homepage. I have this code (index.php):

<?php while ( have_posts() ) : the_post(); ?>
    <?php get_template_part( 'content'); ?>
<?php endwhile; ?>

Unfortunately this displays part or all the post content but not the attached images. How can I change it in order to display them? I don’t want to use the featured image but only the attached ones.

Related posts

1 comment

  1. I actually found a new WordPress function by researching your question. It’s important to know that there are so many different ways to implement what you are asking for and leaving the following code in the form I am inserting below isn’t ideal. This should only be considered a starting point.

    Best practice would be to move it into the content.php file (as @Nilambar mentioned in a comment on your question). Maybe even creating a new file, by duplicating content.php and calling it content-attached-media.php and using it by changing the get_template_part line to get_template_part( 'content', 'attached-media' ).

    Herewith the code to get you started though:

    <?php while ( have_posts() ) : the_post(); ?>
        <?php get_template_part( 'content'); ?>
        <?php
            /*
             * Choose what size the image should be displayed in by setting the $size variable.
             * Some options include 'thumbnail', 'medium', 'large', 'full'
            */
            $size = 'full';
            $attached_images = get_attached_media( 'image', get_the_ID() );
            foreach( $attached_images as $image ) {
                echo wp_get_attachment_image( $image->ID, $size );
            }
        ?>
    <?php endwhile; ?>
    

    Documentation used

    https://codex.wordpress.org/Function_Reference/get_attached_media
    https://codex.wordpress.org/Function_Reference/wp_get_attachment_image
    https://codex.wordpress.org/Function_Reference/the_post_thumbnail

Comments are closed.