如果当前登录的用户没有查看404页面的权限,是否有办法显示该页面?我正在寻找一个PHP方法,类似
if( !current_user_can(\'administrator\') ) { show_404(); exit(); }
我曾想过使用重定向,但我想保持url不变。如果当前登录的用户没有查看404页面的权限,是否有办法显示该页面?我正在寻找一个PHP方法,类似
if( !current_user_can(\'administrator\') ) { show_404(); exit(); }
我曾想过使用重定向,但我想保持url不变。通过在标题中使用以下代码,我可以显示404错误。
<?php
global $wp_query;
$wp_query->set_404();
status_header( 404 );
get_template_part( 404 ); exit();
?>
要分解它:$wp_query->set_404()
: 告诉wp\\U查询这是404,这会更改标题status_header()
: 发送HTTP 404头get_template_part()
: 显示404模板为什么不创建一个显示错误消息的页面,然后将用户重定向到该页面?以下是实现这一目标的简单方法:
打开404.php
归档并将以下行添加到其顶部:
/**
* Template Name: 404 Page
*/
使用创建页面404 Page
样板然后重定向用户:if ( !current_user_can(\'administrator\') ) {
$404_page = get_permalink( $404_page_id );
wp_redirect( $404_page );
exit();
}
您应该为404请求使用页面的原因是:在WP 404中,页面实际上是doesn\'t exists, WP在返回404页之前必须搜索其所有内容,这是对资源的浪费。使用预先配置的页面,可以帮助您更快地运行日志。我有一个类似的要求,我不应该让用户访问作者。基于用户所处角色的php页面。我注册template\\u redirect操作来进行检查,甚至在加载实际页面之前,我也会重定向到404页面。
注册:
add_action( \'template_redirect\', [ $this, \'handle_inactive_users\']);
处理程序:public function handle_inactive_users() {
global $wp_query;
if ( $wp_query->is_author() ) {
$user = $wp_query->get_queried_object();
if ( is_a( $user, \\WP_User::class ) && $user->has_cap( \'inactive\' ) ) {
$wp_query->set_404();
status_header( 404 );
get_template_part( 404 );
exit();
}
}
}
如果您选择仅在模板部分的中间使用以下代码段,则该页面可能已经部分呈现,并且实际上没有重定向到404页面。所以最好在template_redirect
行动-$wp_query->set_404();
status_header( 404 );
get_template_part( 404 );
exit();
您可以将此代码写入文件404.php 在实际使用的主题目录中(wp-content/themes/…/404.php):
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".get_bloginfo(\'url\'));
exit();
?>
此代码必须从文件的开头开始(前面没有任何字符)。链接至原文:How to Redirect your 404 page to the Home Page in WordPress
Wordpress已安装到我的根目录(/根/)。我有一个子域名(dammani.techbrij.com),我想从子域名访问主域名的一些文件。我做了以下事情:include_once(\'/root/wp-config.php\'); include_once(\'/root/wp-load.php\'); include_once(\'/root/wp-includes/wp-db.php\'); 现在,“http://techbrij.com/dammani“工作正常,但是”