block a page from logged out users and redirect to homepage

You have to hook in earlier, I would probably use template_redirect:

add_action( 'template_redirect', 'wpse_74577_redirect' );

function wpse_74577_redirect()
{
    // the code from your question
}