Wordpress 按图像的名称获取url文件

Wordpress 按图像的名称获取url文件,wordpress,Wordpress,大家好我在wordpress的媒体文件夹中有几个图片 保存新图像时,按Wordpress保存,如year/month/name.png /wp-content/uploads/2011/01/matt.png 是否可以按名称查找图像并像这样返回url文件 wp-content/uploads/2011/01/ 我在用这个 <?php $upload_dir = wp_upload_dir(); ?> <img src="<?php ec

大家好我在wordpress的媒体文件夹中有几个图片

保存新图像时,按Wordpress保存,如year/month/name.png

/wp-content/uploads/2011/01/matt.png
是否可以按名称查找图像并像这样返回url文件

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">

/.png“class=”附件帖子缩略图“>
其中,
$precontent
是图像的名称,
$upload_dir['baseurl'];

return/wp content/uploads,但我需要这张图片的年份和月份 所以我有/wp content/uploads/matt.png


有什么想法吗?

您可以创建一个数据库查询,查看wp\u posts表,用post\u type='attachment'筛选行,还可以选择post\u mime\u type,比如'image/%'和guid,比如“%/$precontent”

您必须注意以下情况:

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

图像的完整URL位于列GUID中。您可以将其解析出来并获取所需内容。

如果您试图获取附件的完整路径,请认为附件只是带有
post\u type
=“attachment”的post。这意味着您可以按名称查询它们。另外,请注意,post具有唯一的slug。因此
matt.png将有slug
matt
:)

然后,您只需执行以下操作:

$header\u url=get_attachment\u url\u by_slug('matt');

它将返回文件的完整路径

请注意,
sanitize_title();
将自动将您的姓名转换为slug。因此,如果您上载了一个名为的文件。
Christmas即将来临。png
,wordpress会将其指定为类似
Christmas即将来临的slug。如果您使用
sanitize_title(“圣诞节即将来临”)
结果也将是
圣诞节即将来临
之后,您可以获得完整的url:)

)); $query\u images=新的WP\u查询($args)

echo$query\u图像->发布->guid

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) : '';
}
$args = array(
'post_type' => 'attachment', 
'post_status' => 'inherit',
'post_mime_type' => 'image',
's' => 'image_name.jpg'