I have the following code inside my functions.php
file, to provide a temporary redirect on my entire site (all URLs redirect to the homepage), but exclude the wordpress admin area...
add_action( 'template_redirect', 'wa_redirect_site', 5 );
function wa_redirect_site(){
$url = 'https://' . $_SERVER[ 'HTTPS_HOST' ] . $_SERVER[ 'REQUEST_URI' ];
$current_post_id = url_to_postid( $url );
if ( ! is_page( )) { // Excludes page with this ID, and also the WordPress backend
$id = get_the_ID();
wp_redirect( 'https://wa-leicester.org.uk/', 302 ); // You can change 301 to 302 if the redirect is temporary
exit;
}
}
So far, so good, BUT, I'm using a page builder called Bricks Builder, from within the Wordpress admin area, and the trouble is, when I create a template and try to then edit that template, it redirects to the homepage.
When editing a template, the URL it tried to access is: .../template/115/?bricks=run
Which gives me an ID, but I think I need to find a way to exclude the whole /template/ directory.
The code contains a way to exclude page IDs is_page( ))
so I have tried to add the directory to that, and I've also tried to see if something exists that replaces that such as: is_directory
but I cant seem to find anything about it.
Any help would be massively appreciated!!
CodePudding user response:
You can use is_admin()
to determines whether the current request is for an administrative interface page. The default WordPress customiser isn't considered an admin page.
Additionally a lot of plugins are using Ajax requests (@see AJAX in Plugins), so would want to filter that out.
By default, wp_redirect
(cross-site) or wp_safe_redirect
(locally) are returning a 302.
<?php
add_action( 'template_redirect', function () {
/**
* Determines whether the current request is NOT for an administrative interface page NOR a WordPress Ajax request.
* Determines whether the query is NOT for the blog homepage NOR for the front page of the site.
*
* is_admin() returns true for Ajax requests, since wp-admin/admin-ajax.php defines the WP_ADMIN constant as true.
* @see https://developer.wordpress.org/reference/functions/is_admin/#comment-5755
*/
if ( ! is_admin() && ! wp_doing_ajax() && ! is_home() && ! is_front_page() && ! is_user_logged_in() ) {
/**
* Performs a safe (local) redirect, using wp_redirect().
*
* By default the status code is set to 302.
* @see https://developer.wordpress.org/reference/functions/wp_safe_redirect/#parameters
*/
wp_safe_redirect( home_url() );
exit;
};
} );