首页 文章

Wordpress:按 Headers 排序的get_attached_media('image')

提问于
浏览
3

我希望将所有图像附加到特定帖子 . 这适用于:

$media = get_attached_media('image');

我现在需要的是按照 Headers 对这些图像进行排序 . 我已经可以生成数组中 Headers 的列表:

for ($i = 0; $i < count($media); $i++) {
  get_the_title(array_keys($media)[$i])
}

我不知道如何按 Headers 排序 . 有人可以帮忙吗?

1 回答

  • 5

    最好是获取已经订购的附件而不是对结果数组进行排序,对吗?这将节省您的代码,头痛和处理 .

    如果你看看WP Codex,get_attached_media()调用get_children(),它会调用get_posts()(是的,这很快就升级了) . 在WordPress中,附件(几乎任何东西)本质上都是 post .

    考虑到所有这些,这应该取得 list of images attached to a post ordered by title

    $media = get_posts(array(
        'post_parent' => get_the_ID(),
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'orderby' => 'title',
        'order' => 'ASC'
    ));
    

    Edit: 正如ViszinisAPieter Goosen指出的那样,我直接将调用更改为 get_posts() . 致电 get_children() 毫无意义 .

    Note: 需要 'post_parent' 参数,因此我使用 get_the_ID() 作为其值添加了它 . 请记住, need to be within the loop for get_the_ID() 要检索 current post ID . 在循环外部使用时,应相应地将此参数值更改为上下文 .

相关问题