Advertisement
SergeyBiryukov

Get attachment attributes by URL

Mar 18th, 2014
411
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.74 KB | None | 0 0
  1. function get_attachment_attr_by_url( $image_url ) {
  2.     $uploads = wp_upload_dir();
  3.     $relative_url = str_replace( $uploads['baseurl'] . '/', '', $image_url );
  4.  
  5.     $query = new WP_Query( array(
  6.         'post_type'      => 'attachment',
  7.         'post_status'    => 'any',
  8.         'fields'         => 'ids',
  9.         'posts_per_page' => 1,
  10.         'meta_query' => array(
  11.             array(
  12.                 'key'     => '_wp_attached_file',
  13.                 'value'   => $relative_url,
  14.                 'compare' => 'LIKE'
  15.             )
  16.         )
  17.     ) );
  18.  
  19.     $attachment_id = current( $query->posts );
  20.     if ( ! $attachment_id ) {
  21.         return false;
  22.     }
  23.  
  24.     $attr = array(
  25.         'alt' => trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ),
  26.         'title' => get_the_title( $attachment_id )
  27.     );
  28.  
  29.     return $attr;
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement