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.

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');