Get link of inserted media file of post within loop

You can get attachment URL like this.

<?php if ( have_posts() ) : while (have_posts()) : the_post(); ?>
   <a href="https://wordpress.stackexchange.com/questions/163795/<?php $featured_image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ),"full' ); echo $featured_image_url[0]; ?>">
     <?php the_title(); ?>
   </a>
<?php endwhile; endif; ?>

First you will need to get the attachment ID so you will need to get it from get_post_thumbnail_id and then we can get image data array with wp_get_attachment_image_src by supplying the attachment ID. And will print URL of image from array.

Also this get_post_thumbnail_id will get attachment (image) ID of featured image. It does not depend on how many images you upload in a post. You must assign a featured image to a post.

EDIT:

If you want to print the link of PDF attachment only then you can use this code instead. What this will do is search for all PDF attachments of a post and then print the link of first PDF attachment only. So you don’t need to worry about having more PDF files in a post.

<?php if ( have_posts() ) : while (have_posts()) : the_post();
    $args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => null, 'post_parent' => $post->ID );
    $attachments = get_posts( $args );
    if ( $attachments ) {
        foreach ( $attachments as $attachment ) {
          ?>
              <a href="https://wordpress.stackexchange.com/questions/163795/<?php echo wp_get_attachment_url( $attachment->ID ); ?>"><?php echo get_the_title(); ?></a>
          <?php
        }
    }
endwhile; endif; ?>

EDIT 2

Post this inside WordPress loop or in content.php or loop.php

<?php
    $args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_parent' => $post->ID );
    $attachments = get_posts( $args );
    if ( $attachments ) {
        foreach ( $attachments as $attachment ) {
          ?>
              <a href="https://wordpress.stackexchange.com/questions/163795/<?php echo wp_get_attachment_url( $attachment->ID ); ?>"><?php echo get_the_title; ?></a>
          <?php
        }
    }
?>

Leave a Comment