Check if current user has post in post type and is author role

I want to check to see if the current user has already submitted a post in our custom post type and if they have, and they have the author role then add inline style to the header to hide some things..

Here is what Im trying but it isn’t working and I can’t seem to figure out why?

function chelsea_user_has_posts($user_id) {
  $result = new WP_Query(array(
    'author'=>$user_id,
    'post_type'=>'ait-dir-item',
    'post_status'=>'publish',
    'posts_per_page'=>1,
  ));
  return (count($result->posts)!=0);
}

function cross_check_user_items() {
  $user = wp_get_current_user();
  $chelseaRole = get_the_author_meta('user_level');
  if ($user->ID)
    if (chelsea_user_has_posts($user->ID) && $chelseaRole == 1) {
      echo '<style type="text/css">
               #adminmenuwrap ul#adminmenu li#menu-posts-ait-dir-item.wp-has-submenu ul.wp-submenu li:nth-child(2), body.post-type-ait-dir-item div.wrap h2 a.add-new-h2, #woocommerce-product-data.postbox div.inside div.panel-wrap ul.product_data_tabs li:nth-child(8) {display:none !important;}
             </style>';
  } else {
    //show them the goods
  }
}
add_action('admin_head', 'cross_check_user_items');

All of this of course is in my functions.php file

Thanks for looking 🙂

1 Answer
1

Instead of using $chelseaRole ==1 it should be replaced with something like this !current_user_can('manage_categories') since the author role cannot manage categories as seen here: https://codex.wordpress.org/Roles_and_Capabilities

Polished it would look like this:

function chelsea_user_has_posts($user_id) {
  $result = new WP_Query(array(
    'author'=>$user_id,
    'post_type'=>'ait-dir-item',
    'post_status'=>'publish',
    'posts_per_page'=>1,
  ));
  return (count($result->posts)!=0);
}

function cross_check_user_items() {
  $user = wp_get_current_user();

    if (chelsea_user_has_posts($user->ID) && !current_user_can('manage_categories')) {
      echo '<style type="text/css">
               #adminmenuwrap ul#adminmenu li#menu-posts-ait-dir-item.wp-has-submenu ul.wp-submenu li:nth-child(3), body.post-type-ait-dir-item div.wrap h2 a.add-new-h2, #woocommerce-product-data.postbox div.inside div.panel-wrap ul.product_data_tabs li:nth-child(8) {display:none !important;}
             </style>';
  } else {
    //show them the goods
  }
}
add_action('admin_head', 'cross_check_user_items');

Leave a Comment