I would like to get an image by specifying a certain slug and then echoing that address in the image src code.

The slug for the image would be "book-site-header"

I've looked through the get_wp_attachment and get_wp_attachment_metadata in the wordpress codex but neither makes mention of the slug. Slugs have to be unique and are saved in the DB so it must be possible to find it based on the slug and then get the related file url.

image of slug area

1 Answer 1


An attachment is just a post with the post_status = inherit and the post_type = attachment, so can be queried with WP_Query or get_posts.

Note that slug (post_name) is unique per post type.

$_header = get_posts('post_type=attachment&name=book-site-header&posts_per_page=1&post_status=inherit');
$header = $_header ? array_pop($_header) : null;  
$header_url = $header ? wp_get_attachment_url($header->ID) : '';

you can also use the code above to built your own custom fucntion

function get_attachment_url_by_slug( $slug ) {
  $args = array(
    'post_type' => 'attachment',
    'name' => sanitize_title($slug),
    'posts_per_page' => 1,
    'post_status' => 'inherit',
  $_header = get_posts( $args );
  $header = $_header ? array_pop($_header) : null;
  return $header ? wp_get_attachment_url($header->ID) : '';

and then

$header_url = get_attachment_url_by_slug('book-site-header');
  • I've tried both routes, adding the function into the function file and then calling it with $header_url. This resulted in a server error. I also tried the first option with get_posts, but this resulted in not loading anything below it. I echoed $header_url.
    – Alexnl
    Commented Sep 23, 2013 at 15:51
  • There was a typo in both code, just fixed. Try now, it work (tested). @Alexnl
    – gmazzap
    Commented Sep 23, 2013 at 16:03
  • That worked perfectly!! Thank you very much for your quick help! I will make sure to send you a copy of the ebook when it comes out, as appreciation. www.thesussexdeal.com
    – Alexnl
    Commented Sep 23, 2013 at 19:01
  • For newer version of wordpress 5 change name to post_title
    – 0x1gene
    Commented Apr 27, 2019 at 13:49
  • 1
    @0x1gene name is still valid query parameter for post slug: see codex.wordpress.org/Class_Reference/… if you want to query post title there's the title parameter.
    – gmazzap
    Commented Apr 29, 2019 at 6:50

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.