NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

WordPress: Redirecting a Private Page to Customer Account Page
Easy
Web Hosting Canada

Last modified : Oct 01 2022

Estimated reading time : 1 minute, 21 seconds - 163 words

With this tutorial, we will create a function that will redirect a private page. By default all private pages are password protected and limited to WordPress users. If non-connected users try to access it, it redirects to a 404.

While we want to keep the same default conditions when we’re testing our page privately, we want to redirect it to our homepage.

With the new function that we need to add into our functions.php file, we need to validate two conditions: first if we land on the 404 and then we validate that our query is valid for a private page.

WordPress: Redirect Private Page to Customer Account Page

////////////////////////////////// Redirect private page  ////////////////////////////////////////

add_action('template_redirect', 'themespress_private_content_redirect_to_login', 9);
function themespress_private_content_redirect_to_login() {
  global $wp_query, $wpdb;
  if (is_404()) {
    $private = $wpdb->get_row($wp_query->request);
    $location = home_url();
    if( 'private' == $private->post_status  ) {
      wp_safe_redirect($location);
      exit;
    }
  }
}

As you can see, we are fulfilling the requirements and now we need to create a new variable that we’ll call $location and determine the redirect path. On our example, we used home_url().

When we validate that is a private page, we trigger the wp_safe_redirect from the $location variable.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>