我有一个函数可以在一个页面上显示媒体库中的所有图像。我想显示每个图像的日期,但使用get\\u the\\u date()只返回今天的日期。
下面是我使用的代码:
function get_images_from_media_library() {
$args = array(
\'post_type\' => \'attachment\',
\'post_mime_type\' =>\'image\',
\'post_status\' => \'inherit\',
\'order\' => \'DESC\'
);
$query_images = new WP_Query( $args );
$images = array();
foreach ( $query_images->posts as $image) {
$images[]= $image->guid;
}
return $images;
}
function display_images_from_media_library() {
$imgs = get_images_from_media_library();
$html = \'<div id="media-gallery">\';
foreach($imgs as $img) {
$html .= \'<img src="\' . $img . \'" alt="" />\';
echo get_the_date(\'F j, Y\');
}
$html .= \'</div>\';
return $html;
}
有人能告诉我哪里出了问题吗?
SO网友:s_ha_dum
get_the_date
取决于全球$post
变量这有点难说,但如果你看看source for get_the_date
您将看到它使用get_post
和it assumes $post
if no other parameters are given.
您的代码从未设置global $post
变量,除非WP_Query
最初运行。您需要重构。我会从get_images_from_media_library
并构建一个更标准的循环来处理它们。
我认为这应该更好。
function get_images_from_media_library() {
$args = array(
\'post_type\' => \'attachment\',
\'post_mime_type\' =>\'image\',
\'post_status\' => \'inherit\',
\'order\' => \'DESC\'
);
$query_images = new WP_Query( $args );
return $query_images;
}
function display_images_from_media_library() {
$imgs = get_images_from_media_library();
$html = \'<div id="media-gallery">\';
global $post;
if ($imgs->have_posts()) {
while($imgs->have_posts()) {
$imgs->the_post();
$html .= \'<img src="\' . $post->guid . \'" alt="" />\';
$html .= get_the_date(\'F j, Y\');
}
}
$html .= \'</div>\';
return $html;
}
echo display_images_from_media_library();