Show different home page based on user role

2019-08-31 06:49发布

问题:

I'm trying to show different homepages based on the user role. I have 4 differents pages:

Home - Default one Home 1 - User role 1 Home 2 - User role 2 Home 3 - User role 3

The problem i have right now is to show the pages for the user roles.

This is the function i'm using for check the user role.

function get_user_role(){
    if (is_user_logged_in()) {
        global $current_user;
        $user_roles = $current_user->roles;
        $user_role = array_shift($user_roles);
        return $user_role;
    }else{
        return "subscriber";
   } 
}

Also i'm showing the page called "Home" to show on homepage using in the page.php

is_front_page()

But.. How can i show the other pages instead of the default front page?

Thanks in advance

回答1:

You can use the get_template_part() function:

get_template_part('home', get_user_role());

Using WordPress’s template hierarchy, if the current user’s role was Administrator then the template would first look for home-administrator.php, and if that was not found then it would just fall back to home.php.



回答2:

First set the (static) front page to a default setting, then use the option filter to override the setting depending on the user.

add_filter('option_page_on_front', 'your_override_function');
function your_override_function($page_id) {
   if (get_user_role == 'some_value') {
      return some_page_id;
   }
   return $page_id;
}


标签: php wordpress