Wordpress重定向-函数.排除目录



我的functions.php文件中有以下代码,用于在我的整个网站上提供临时重定向(所有URL重定向到主页(,但不包括wordpress管理区域。。。

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;
} 
}

到目前为止,一切都很好,但是,我正在Wordpress管理区域使用一个名为Bricks builder的页面生成器,问题是,当我创建一个模板并尝试编辑该模板时,它会重定向到主页。

编辑模板时,它尝试访问的URL为:/模板/115/?砖块=运行

这给了我一个ID,但我认为我需要找到一种方法来排除整个/template/目录。

该代码包含一种排除页面IDis_page( ))的方法,因此我尝试将目录添加到该目录中,还尝试查看是否存在替代该目录的内容,例如:is_directory,但我似乎找不到任何关于它的信息。

任何帮助都将不胜感激!!

您可以使用is_admin()来确定当前请求是否针对管理接口页面。默认的WordPress自定义程序不被视为管理页面。

此外,很多插件都在使用Ajax请求(请参阅插件中的Ajax(,所以我们想过滤掉这些请求。

默认情况下,wp_redirect(跨站点(或wp_safe_redirect(本地(返回一个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;
};
} );