get the url file by name of image

Hi everyone I have several image in my media folder in wordpress

when a save a new image WordPress save like year/month/name.png

Read More
/wp-content/uploads/2011/01/matt.png

It is possible find the image by name and return the url File like this?

wp-content/uploads/2011/01/

I am using this

    <?php $upload_dir = wp_upload_dir(); ?>
            <img src="<?php echo $upload_dir['baseurl']; ?>/<?php echo $precontent; ?>.png " class="attachment-post-thumbnail">

where $precontent is the name of image and $upload_dir['baseurl'];

return /wp-content/uploads but I need the year and month of this image
so I have /wp-content/uploads/matt.png

any idea?

Related posts

Leave a Reply

3 comments

  1. If you’re trying to get the full path of the attachment think that an attachment is just post with post_type = ‘attachment’. That means you can query for them by name. Also, note that posts have unique slugs. So matt.png will have the slug matt 🙂

    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 you just have to do the following:

    $header_url = get_attachment_url_by_slug('matt');

    which will return the full path of your file.

    Note that sanitize_title(); will auto-transform your name into a slug. So if you uploaded a file with the name. Christmas is coming.png, wordpress would have designated it a slug like christmas-is-coming. And if you use sanitize_title('Christmas is coming'); the result would also be christmas-is-coming and after that you can get the full url. 🙂

  2. You can create a database query looking at the wp_posts table, filtering rows with post_type = ‘attachment’, optionally post_mime_type like ‘image/%’ and a guid like “%/$precontent”

    You will have to take care of situations where there is:

    /wp-content/uploads/2011/01/matt.png
    /wp-content/uploads/2011/02/matt.png
    

    The full URL of the image is found in the column GUID. You can parse it out and get what you need.

  3. $args = array(
    'post_type' => 'attachment', 
    'post_status' => 'inherit',
    'post_mime_type' => 'image',
    's' => 'image_name.jpg'
    

    );
    $query_images = new WP_Query( $args );

    echo $query_images->post->guid;