GET_POSTS提供的结果与wpdb->GET_RESULTS不同

时间:2018-03-24 作者:Beee

我遇到了一些让我完全困惑的事情。对于cron作业,我需要检索哪些用户被“标记”为VIP,然后从这些VIP用户检索帖子。

global $wpdb;
$capabilities_field_name = $wpdb->prefix . \'capabilities\';
$user_args = [
    \'meta_query\' =>
        [
            \'relation\' => \'OR\',
            [
                \'key\'     => $capabilities_field_name,
                \'value\'   => \'"independent_pro"\',
                \'compare\' => \'LIKE\',
            ],
            [
                \'key\'     => $capabilities_field_name,
                \'value\'   => \'agency_pro\',
                \'compare\' => \'LIKE\',
            ],
        ],
    \'fields\' => \'ID\',
    \'number\' => 999, // to select all users
    \'exclude\' => [1], // admin user
];

$user_query = new WP_User_Query( $user_args ); 
$pro_users  = $user_query->get_results();
// $pro_users = array with 2 user ids: 21 and 44

if ( count( $pro_users ) > 0 ) {
    $pro_users = implode( \',\', $pro_users ); 
    $pro_ads   = get_posts( array(
        \'post_type\'   => PostTypes::PROFILE,
        \'number\'      => -1,
        \'author\'      => $pro_users, 
        \'post_status\' => [ \'publish\', \'pending\' ],
    ) );
    // result = 5 posts (which is incorrect)

    $pro_users = implode( \',\', $pro_users );
    $pro_ads   = get_posts( array(
        \'post_type\'   => PostTypes::PROFILE,
        \'number\'      => -1,
        \'author\'      => 21
        \'post_status\' => [ \'publish\', \'pending\' ],
    ) );
    // result = 2 posts (which is correct)

    $pro_users = implode( \',\', $pro_users );
    $pro_ads   = get_posts( array(
        \'post_type\'   => PostTypes::PROFILE,
        \'number\'      => -1,
        \'author\'      => 44
        \'post_status\' => [ \'publish\', \'pending\' ],
    ) );
    // result = 4 posts (which is correct)

    $pro_ads = $wpdb->get_results(
        "
            SELECT * 
            FROM $wpdb->posts
            WHERE post_status IN (\'publish\',\'pending\') 
                AND post_type = \'profile\' 
                AND post_author IN ({$pro_users}) 
            LIMIT 1000
            "
    );
    // result = 6 posts (which is correct)
}
是的,我停用了所有插件,然后切换回Twentysventen进行测试。。。没有变化。控制台或日志中也没有错误。

1 个回复
最合适的回答,由SO网友:Beee 整理而成

为什么我总是花几个小时寻找解决方案。。。然后把它贴在这里,几分钟内我自己就找到了解决方案。。。。

我在中找到了解决方案this post.

get\\u posts()函数的默认参数包括“numberposts”=>5。

所以当我设置数字时,它被忽略了,并且为numberposts设置了5。正确的值为posts_per_pagenumberposts (imo是一个选择不当的变量)。

结束

相关推荐