2

I ran into something that has me completely stumped. For a cron job I need to retrieve which users are 'marked' as VIP and then retrieve the posts from these VIP users.

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)
}

Yes, I deactivated all plugins and I switched back to twentysventeen to test it... No change. No errors in console or log either.

1 Answer 1

1

Why is it always that I look for a solution for hours... then post it here and within a few minutes I find the solution myself....

I found the solution in this post.

The default arguments for get_posts() function include 'numberposts' => 5.

So when I set number, it was ignored and 5 was set for numberposts. The correct values are posts_per_page and numberposts (imo a poorly chosen variable).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.