Search code examples
phpwordpressuser-roles

How to call all articles in get_posts() include


I want to get posts by WP user level. I use get_posts() for getting posts and in arguments I use include parameter.

Like this:

$private = array(
              'numberposts' => $st_cat_post_num,
              'orderby' => $st_posts_order,
              'category__in' => $st_sub_category->term_id,
              'include' => $kbsofs_posts_arr,
              'post_status' => 'publish',
           );

Here is my Complete code:

global $current_user;
$kbsofs_posts = '';
if($current_user->user_level == 0) {
     $kbsofs_posts = "1,2,3 ...."; // Post IDs
} else if($current_user->user_level == 1) {
     $kbsofs_posts = "10,20,30 ...."; // Post IDs
}  else if($current_user->user_level == 2) {
     $kbsofs_posts = "100,200,300 ...."; // Post IDs
} else {
     $kbsofs_posts = '';
}
$kbsofs_posts_arr = explode(',',$kbsofs_posts);

$private = array(
               'numberposts' => $st_cat_post_num,
               'orderby' => $st_posts_order,
               'category__in' => $st_sub_category->term_id,
               'include' => $kbsofs_posts_arr,
               'post_status' => 'publish',
           );
//print_r($private);
$st_cat_posts = get_posts($private);

When I login as a subscriber or contractor or author it gives me exact articles what I want. But when I loged in as administrator it gives me nothing (I think its not working because of my else condition).

I also try this:

$post_include = '';
if($current_user->user_level != 10 || $current_user->user_level != 9 || $current_user->user_level != 8) {
     $post_include = "'include' => $kbsofs_posts_arr";
}
$private = array(
               'numberposts' => $st_cat_post_num,
               'orderby' => $st_posts_order,
               'category__in' => $st_sub_category->term_id,
               $post_include,
               'post_status' => 'publish',
           );

But it also gives me nothing. So please tell me how can i get all articles in my else condition.


Solution

  • Your issue is that you set includes to an empty string if the user isnt included in your if blocks, meaning no posts are inlcuded.

    Better to only use the include key if needed:

    global $current_user;
    
    $private = array(
        'numberposts' => $st_cat_post_num,
        'orderby' => $st_posts_order,
        'category__in' => $st_sub_category->term_id,
        'post_status' => 'publish',
    );
    
    if($current_user->user_level == 0) {
        $private['include'] = [1,2,3];
    } else if($current_user->user_level == 1) {
        $private['include'] = [10,20,30];
    }  else if($current_user->user_level == 2) {
        $private['include'] = [100,200,300];
    } 
    
    $st_cat_posts = get_posts($private);