通过图像名称获取 url 文件
大家好,我在 wordpress 的媒体文件夹中有几张图片
Hi everyone I have several image in my media folder in wordpress
当保存一个新图片 Wordpress 保存为年/月/名称.png
when a save a new image Wordpress save like year/month/name.png
/wp-content/uploads/2011/01/matt.png
可以通过名称找到图像并返回这样的url文件吗?
It is possible find the image by name and return the url File like this?
wp-content/uploads/2011/01/
我正在使用这个
<?php $upload_dir = wp_upload_dir(); ?>
<img src="<?php echo $upload_dir['baseurl']; ?>/<?php echo $precontent; ?>.png " class="attachment-post-thumbnail">
其中 $precontent
是图像的名称和 $upload_dir['baseurl'];
where $precontent
is the name of image and $upload_dir['baseurl'];
返回/wp-content/uploads 但我需要这张图片的年份和月份所以我有/wp-content/uploads/matt.png
return /wp-content/uploads but I need the year and month of this image so I have /wp-content/uploads/matt.png
有什么想法吗?
如果您想获取附件的完整路径,请认为附件只是使用 post_type
= 'attachment' 发布.这意味着您可以按名称查询它们.另请注意,帖子具有独特的 slug.所以 matt.png
会有 slug matt
:)
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.
请注意,sanitize_title();
会将您的名字自动转换为 slug.因此,如果您上传了具有该名称的文件.Christmas iscoming.png
,wordpress 会把它指定为像 christmas-is-coming
这样的 slug.如果您使用 sanitize_title('Christmas iscoming');
结果也将是 christmas-is-coming
之后您可以获得完整的 url.:)
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. :)