I have a custom meta box to store pdf files. For this input, I'm using type="media" to acess wordpress media library.

Now I can't get the file name. Here is my entire loop:

        $args_artigos = array('post_type' => 'artigo','posts_per_page' => -1);
        $artigos_posts = new WP_Query($args_artigos);

        if($artigos_posts->have_posts()) : 
           while($artigos_posts->have_posts()) : 
        <a href="<?php the_permalink(); ?>" class="artigos-titulo"><?php the_title() ?></a>
        <span class="artigos-autor"><?php echo esc_html( get_post_meta( get_the_ID(), 'autor', true ) ); ?></span>
        <?php $filename = basename ( get_attached_file( get_the_ID() ) ); echo $filename; ?>


        <?php endwhile; else: ?>
           Oops, there are no posts.
        <?php endif; ?>

But it's return no data.

  • see this answer.
    – Milo
    Nov 11, 2013 at 16:48
  • @Milo same error. See my entire loop. Nov 11, 2013 at 16:55
  • Unless I'm missing something, your first code block isn't included in your second code block (entire loop markup). Nov 11, 2013 at 16:58
  • you can't just copy/paste that code into yours, you need to pass the ID you get back from your meta data to get_attached_file.
    – Milo
    Nov 11, 2013 at 17:00
  • @ChipBennett I changed it. The attachment file name is stored in postmeta table with _wp_attached_file as meta_key. So I change the code. But have no success. Nov 11, 2013 at 17:02

1 Answer 1


Your meta field contains the ID of the attachment, you need to fetch that ID, then get the filename using that attachment ID.

$doc_id = get_post_meta( get_the_ID(), 'pdf', true );
$filename = basename( get_attached_file( $doc_id ) );
echo $filename;
  • Thanks Milo. This is exactly what I need. Just onde question: is possible to get the attachment url? Nov 11, 2013 at 17:14
  • "is possible to get the attachment url" - the Codex is your friend. Nov 11, 2013 at 17:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.