<?php
/*
* Plugin Name: Alternate Home Page by User Role
* Description: Allows you to select an alternate home page for each user role.
* Version: 1.0
* Author: John Doe
* Author URI: https://example.com
*/
function ahp_template_redirect() {
// Get the current user's role
$user = wp_get_current_user();
$user_role = $user->roles[0];
// Get the selected home page for the user's role
$home_page = get_option('ahp_home_page_' . $user_role);
// If a home page is selected, redirect the user to it
if (!empty($home_page)) {
wp_redirect(get_permalink($home_page));
exit;
}
}
add_action('template_redirect', 'ahp_template_redirect');
function ahp_settings_page() {
// Check if the user has the proper permissions to access the settings page
if (!current_user_can('manage_options')) {
wp_die(__('You do not have sufficient permissions to access this page.'));
}
// Get all available user roles
global $wp_roles;
$roles = $wp_roles->get_names();
// Check if the form has been submitted
if (isset($_POST['ahp_submit'])) {
// Save the selected home page for each user role
foreach ($roles as $role_value => $role_name) {
$home_page = sanitize_text_field($_POST['ahp_home_page_' . $role_value]);
update_option('ahp_home_page_' . $role_value, $home_page);
}
}
// Display the settings form
?>
<div class="wrap">
<h1><?php _e('Alternate Home Page by User Role Settings'); ?></h1>
<form method="post">
<table class="form-table">
<tbody>
<?php foreach ($roles as $role_
value => $role_name) {
// Get the selected home page for the current user role
$home_page = get_option('ahp_home_page_' . $role_value);
?>
<tr>
<th scope="row"><?php echo $role_name; ?></th>
<td>
<?php
// Display a dropdown with all available pages
wp_dropdown_pages(array(
'selected' => $home_page,
'name' => 'ahp_home_page_' . $role_value,
'show_option_none' => __('- None -'),
));
?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<p class="submit">
<input type="submit" name="ahp_submit" class="button button-primary" value="<?php _e('Save Changes'); ?>">
</p>
</form>
</div>
<?php
}
function ahp_settings_link($links) {
// Add a link to the settings page to the plugin actions links
$settings_link = '<a href="options-general.php?page=ahp_settings">' . _('Settings') . '</a>';
array_unshift($links, $settings_link);
return $links;
}
add_filter('plugin_action_links' . plugin_basename(FILE), 'ahp_settings_link');
function ahp_add_settings_page() {
// Add the settings page to the Settings menu
add_options_page(
__('Alternate Home Page by User Role'),
__('Alternate Home Page'),
'manage_options',
'ahp_settings',
'ahp_settings_page'
);
}
add_action('admin_menu', 'ahp_add_settings_page');