loop through posts and display inserted media and post title as a link

by user49869   Last Updated January 31, 2019 16:08 PM

I'm fiddling around with an issue I cannot solve. Inside the loop I would like to find the URL of an inserted media file (pdf, doc etc) and display this as an anchor. Furthermore I would like to display the title of the current post as content of the link. My attempt so far:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?> 
     <a href="<?php wp_get_attachment_url(); ?>"><?php the_title(); ?></a>
<?php endwhile; ?>
<?php endif; ?>

displaying the title works totally fine. But the href="" does not show up anything. Thanks

Note: It is a media file simply inserted as post content, not a featured image or something.

Answers 1

I took a quick peek at the other question referenced in other comments, and the gist of how you loop through attachments there meshes with what is shown in the wp_get_attachment_image documentation example. In a nutshell, any attachments on a particular post will reference that post by ID.

In particular, it's crucial to understand that attachments are also posts themselves of the post type attachment. Inside your main loop, you'll get your attachments by running a nested query for all attachments whose post parent is equal to the ID of your outer loop's post:

// Our main (outer) query:
while(have_posts()) {

    $nested_query = new WP_Query(array(
        "post_type" => "attachment",
        "post_status" => "inherit",
        "posts_per_page" => -1,
        "post_parent" => get_the_ID()  // attachments belonging to the post we're looking at
    $attachments = $nested_query->get_posts();  // get an array of post objects for each attachment
    foreach($attachments as $att_post) {
        printf("<a href='%s'>%s</a>", wp_get_attachment_url($att_post->ID), get_the_title());

I doubt the above does what you want it to, primarily because I don't think you want to echo an anchor for every single attachment that has the post title for its text. However, for illustrative purposes, this is how you could loop through attachments nested within a post loop.

Justin Bell
Justin Bell
October 09, 2014 13:27 PM

Related Questions

automatically move to media library

Updated October 09, 2018 18:08 PM

How to change image url?

Updated February 25, 2017 16:08 PM

how to get custom attachment url?

Updated May 15, 2019 08:08 AM

Remove product category placeholder image (Woocomerce)

Updated December 13, 2018 16:08 PM