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?
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. Somatt.png
will have the slugmatt
🙂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 likechristmas-is-coming
. And if you usesanitize_title('Christmas is coming');
the result would also bechristmas-is-coming
and after that you can get the full url. 🙂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:
The full URL of the image is found in the column GUID. You can parse it out and get what you need.
);
$query_images = new WP_Query( $args );
echo $query_images->post->guid;