You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用post_author参数调用get_posts返回0结果问题

WordPress 4.4.11中get_posts指定post_author返回0结果的解决办法

当前使用WordPress 4.4.11版本,调用get_posts()时,指定自定义文章类型参数能正常返回预期结果:

$args = array(
    'posts_per_page'   => -1,
    'paged'            => 0,
    'orderby'          => 'post_date',
    'order'            => 'DESC',
    'post_status'      => array('publish'),
    'post_type'        => 'my_custom_post_type'
    //'post_author' => 3
);

$posts_array = get_posts($args); 

$s_count = count($posts_array);

echo $s_count;

但去掉post_type参数并添加post_author => 3后,尽管wp_posts表中存在大量该作者的帖子,却返回0条结果:

$args = array(
    'posts_per_page'   => -1,
    'paged'            => 0,
    'orderby'          => 'post_date',
    'order'            => 'DESC',
    'post_status'      => array('publish'),
    //'post_type' => 'my_custom_post_type'
    'post_author'      => 3
);

$posts_array = get_posts($args); 

$s_count = count($posts_array);

echo $s_count;

问题原因

WordPress 4.4.11版本中,get_posts()函数的默认post_type为'post'(仅查询系统默认的文章类型)。如果该作者的帖子属于页面(page)、自定义文章类型而非默认post类型,不指定post_type时就无法查询到这些内容,最终返回0条结果。

解决办法

  1. 查询所有文章类型
    显式将post_type设为'any',这样会查询所有已注册的文章类型:

    $args = array(
        'posts_per_page'   => -1,
        'paged'            => 0,
        'orderby'          => 'post_date',
        'order'            => 'DESC',
        'post_status'      => array('publish'),
        'post_type'        => 'any',
        'post_author'      => 3
    );
    
  2. 指定具体需要的文章类型
    如果你清楚该作者帖子所属的类型,可以直接传入类型数组,比如包含默认文章、页面和自定义类型:

    'post_type' => array('post', 'page', 'my_custom_post_type')
    
  3. 排查钩子干扰
    部分主题或插件可能通过pre_get_posts钩子修改了get_posts的查询逻辑,导致结果被过滤。可以临时禁用所有插件、切换到WordPress默认主题(如Twenty Sixteen)测试,确认是否是第三方代码导致的问题。

内容的提问来源于stack exchange,提问作者Jobbie Daddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 20:22:21