WordPress函数:WP_Query 如何搜索媒体库(附件)

追格官方小助手/ 2022年07月12日/ WordPress/ 浏览 1205

在WordPress中,如果想要查询出所有的图片文件,该怎么办呢?


我们已经知道,图片、视频等的信息都是存储在 wp_posts 表中的,即在WordPress看来,这些也是“文章”。既然是文章,就可以用WP_Query查询。


WP_Query 支持 post_mine_type 参数,即按文章的 mine 类型筛选(只对 attachment 类型的文章有效)。


比如,查询出所有的gif图片:


$args = array(
    'post_type'  => 'attachment',
    'post_status'    => 'inherit',
    'post_mime_type' => 'image/gif',
);
$query = new WP_Query( $args );


注意:attachment 的 post_status 都是 inherit 。


查询出所有的非图片文件:


$unsupported_mimes  = array( 'image/jpeg', 'image/gif', 'image/png', 'image/bmp', 'image/tiff', 'image/x-icon' );
$all_mimes          = get_allowed_mime_types();
$accepted_mimes     = array_diff( $all_mimes, $unsupported_mimes );
$args           = array(
    'post_type'         => 'attachment',
    'post_status'       => 'inherit',
    'post_mime_type'    => $accepted_mimes,
);
$query          = new WP_Query( $query_args );


WP_Query 的基础用法可以参考文章:WP_Query 的基础用法简介

发表评论

暂无评论,抢个沙发...

客服 工单