Wordpress get_posts()未返回post_type=attachment的所有帖子


Wordpress get_posts() not returning all posts with post_type=attachment

我正在尝试从Wordpress的媒体库中获取所有视频的列表。我在常规WP循环之外做这件事,因此包括WP-load.php。然而,我收到了0个带有此代码的帖子(尽管实际上有4个视频):

include('../../../wp-load.php');
$args = array( 
  'post_type' => 'attachment', 
  'post_mime_type' => 'video', 
  'numberposts' => -1, 
  'posts_per_page'=>-1, 
  'suppress_filters' => true, 
  'post_status' => 'any', 
  'post_parent' => null
); 
$attachments = get_posts( $args );
echo(count($attachments));
if ( $attachments ) {
    foreach ( $attachments as $post ) {
        setup_postdata( $post );
        the_title();
        echo('<br />');
        echo wp_get_attachment_url( $post->ID, false );
        echo('<br /><br />');
    }
    wp_reset_postdata();
}

然而,这个问题似乎与视频无关(或仅与视频有关):如果我从查询中删除'post_mime_type' => 'video'参数,我的媒体库中只返回了16个附件,而不是121个附件(图像、声音、视频)。我真的开始对这个问题失去理智了。。。

Heureka!经过几个小时的尝试,我发现了这个问题的原因:插件Polylang

长话短说,如果在Wordpress安装中安装了Polylang,那么似乎必须为get_posts()函数提供另一个参数:它被称为lang

它可以是一个空字符串,用来简单地列出所有资产,也可以是Polylang在特定Wordpress安装中使用的特定语言标记之一。因此,最终工作的代码必须是这样的:

include('../../../wp-load.php');
$args = array('lang' => '', 'post_type' => 'attachment', 'post_mime_type' => 'video', 'numberposts' => -1, 'posts_per_page'=>-1, 'suppress_filters' => true, 'post_status' => 'any', 'post_parent' => null); 
$attachments = get_posts( $args );
echo(count($attachments));
if ( $attachments ) {
    foreach ( $attachments as $post ) {
        setup_postdata( $post );
        the_title();
        echo('<br />');
        echo wp_get_attachment_url( $post->ID, false );
        echo('<br />');echo('<br />');
    }
    wp_reset_postdata();
}

我真的希望这能帮助别人节省一些宝贵的时间!

此链接有助于找到我的解决方案:http://polylang.wordpress.com/documentation/documentation-for-developers/general/