get the url file by name of image
wordpress
Solution
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. :)
Problem
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 ``` /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?