Get attachment by slug

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

Leave a Comment

tech