大家好,我在wordpress的媒体文件夹中有几张图片
当保存新图像时Wordpress保存为年/月/名.png
/wp-content/uploads/2011/01/matt.png
可以按名称查找图像,并像这样返回网址文件吗?
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'];
return / wp-content / uploads但我需要这张图片的年份和月份 所以我有/wp-content/uploads/matt.png
任何想法?
答案 0 :(得分:10)
如果您尝试获取附件的完整路径,请认为附件只是发布了post_type
='附件'。这意味着您可以按名称查询它们。另外,请注意帖子有独特的slu ..所以matt.png
会有slu 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) : '';
}
然后你必须做以下事情:
$header_url = get_attachment_url_by_slug('matt');
将返回文件的完整路径。
请注意,sanitize_title();
会将您的名称自动转换为slug。所以如果你上传了一个带有名字的文件。 Christmas is coming.png
,wordpress会指定它像christmas-is-coming
这样的slu ..如果您使用sanitize_title('Christmas is coming');
,结果也会是christmas-is-coming
,然后您就可以获得完整的网址。 :)
答案 1 :(得分:0)
你可以创建一个查看wp_posts表的数据库查询,使用post_type ='attachment'过滤行,可选择像'image /%'这样的post_mime_type和像“%/ $ precontent”这样的guid
您必须处理以下情况:
/wp-content/uploads/2011/01/matt.png
/wp-content/uploads/2011/02/matt.png
图片的完整网址位于GUID列中。你可以解析它并获得你需要的东西。
答案 2 :(得分:0)
$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;