WP can’t redirect after you have already output HTML – so move your if/else to the top, before you call for the header, and only output the header & footer if your condition is met.
Also, instead of using current_user_can('role')
, use current_user_can('capability')
– i.e.
<?php if(
current_user_can('activate_plugins') ||
current_user_can('edit_a_defined_custom_post_type')
) {
get_header(); ?>
<div>Restricted content here</div><?php
get_footer();
} else {
wp_redirect(wp_login_url());
} ?>
(According to the Codex, “While checking against particular roles in place of a capability is supported in part, this practice is discouraged as it may produce unreliable results.”)