Some Useful WordPress code snippets.

Non-Admin Redirect

Place the following code in your themes functions.php file. When a non-admin user logs in to your site, they will be redirected to the home page.

function redirect_non_admin() {
    if (! current_user_can('manage_options')) {
        wp_redirect( home_url() ); exit;
    }
}
add_action('admin_init', 'redirect_non_admin');

Displaying a Coming Soon Page for all users who are not logged in.

Place the following code in your themes functions.php file. When a user visits your website he will be redirected to the coming soon page.
The following code assumes that you have created a page on your site with the slug coming-soon.

function coming_soon_redirect() {
    global $pagenow;
    if(!is_user_logged_in()) {
        wp_redirect(home_url("coming-soon"));//Site must have a page with slug coming-soon
        exit;
    }
}
add_action('template_redirect', 'coming_soon_redirect');

Displaying a temporary offline message

Place the following code in your themes functions.php file. It will display a short message while you are working on the website.

function back_soon() {
    if (current_user_can('manage_options')) return;
        wp_die('<h2>We are performing an upgrade to our site - should be back up in a few hours.</h2>');
}
add_action('wp', 'back_soon');

 

Pin It on Pinterest

Share This