Dynamic homepage according to user role

To use a different page’s content on the homepage based on a logged-in user’s role you can do this:

In your functions.php file add this code:

function wpse_273872_pre_get_posts( $query ) {
  if ( $query->is_main_query() && is_user_logged_in() ) {
    //work-around for using is_front_page() in pre_get_posts
    //known bug in WP tracked by https://core.trac.wordpress.org/ticket/21790
    $front_page_id = get_option('page_on_front');
    $current_page_id = $query->get('page_id');
    $is_static_front_page="page" == get_option('show_on_front');

    if ($is_static_front_page && $front_page_id == $current_page_id) {
      $current_user = wp_get_current_user();
      $user = new WP_User($current_user->ID);
      if (in_array('cs_candidate', $user->roles)) { //assuming the role name is cs_candidate
        $query->set('page_id', [page-id-for-candidate-homepage]);
      } elseif (in_array('cs_employer', $user->roles)) { //assuming the role name is cs_employer
        $query->set('page_id', [page-id-for-employer-homepage]);
      }
    }
  }
}
add_action( 'pre_get_posts', 'wpse_273872_pre_get_posts' );

What this does is:

  1. Filters the wp_query args if a user is logged in, you’re on the homepage and it’s the main query
  2. If the user has the role ‘candidate’, set the post id (p) to the ID of the page you created and change the post_type to ‘page’
  3. Similarily, if the user has a role employer, use the ID for that page.

Thanks for helping clarify all your points.

Leave a Comment