Php 404在Wordpress中通过先检查数据库然后转到适当的文件夹来防止
我需要尽可能多地防止网站出现404。其中一些只是打字错误或坏链接。有些只是不断发生的业务联系变化。我已经试着让htaccess中的一些代码变得智能,以捕获这些东西 但是,我有几个404页面经常这样变化: example.com/lorem ipsum/directory/blahblah/Php 404在Wordpress中通过先检查数据库然后转到适当的文件夹来防止,php,wordpress,.htaccess,Php,Wordpress,.htaccess,我需要尽可能多地防止网站出现404。其中一些只是打字错误或坏链接。有些只是不断发生的业务联系变化。我已经试着让htaccess中的一些代码变得智能,以捕获这些东西 但是,我有几个404页面经常这样变化: example.com/lorem ipsum/directory/blahblah/ example.com/dolor-foo/directory/whatever/ 因此,我想在 example.com/********/directory/\br> 转到 example.com/****
example.com/dolor-foo/directory/whatever/ 因此,我想在
example.com/********/directory/\br> 转到
example.com/******/
然而,我认为这必须以某种方式在WP中完成,因为它需要首先检查DB,然后决定重定向到该文件夹。有办法做到这一点吗 我试过这个,但不起作用:
function get_page_by_name($pagename)
{
$pages = get_pages();
foreach ($pages as $page)
{
if ($page->post_name == $pagename)
return $page;
}
return false;
}
function smarter_404s($location, $status) {
//if we get a 404 for a /whatever/directory/something or /whatever/directory/ then go to /whatever/ if it exists
if ($status == 404) {
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$path_parts = explode('/', path);
if (!empty($path_parts[1])) {
$page = get_page_by_name($path_parts[0]);//see if it exists
if (!empty($page)) {
//this page exists, so we can redirect to it
return $location = '/' . $path_parts[0] . '/';//change the location
}
}
}
}
add_filter( 'wp_redirect', 'smarter_404s' );
你所追求的大部分东西都已经被别人完成了。钩住过滤器,确保按如下方式调用它,以便访问第二个
$requested\u url
参数
add_filter( 'redirect_canonical', 'smarter_404s', 10, 2 );
修改回调以接受第二个参数,如下所示
function smarter_404s( $redirect_url, $requested_url ) {
if ( is_404() ) {
//match $requested_url against your path pattern and return the url you want the user to be redirected to
}
return $redirect_url;
}
并在if
块中返回您选择的重定向url
更新
但是,以上仅适用于部分URL匹配。你必须用钩子钩住动作钩才能抓住剩下的部分
function smarter_404s( $redirect_url, $requested_url = '' ) {
if ( is_404() ) {
//if $requested_url is empty the call came from the template_redirect hook
if( empty( $requested_url ) ) {
//match REQUEST_URI and do your redirect using wp_redirect
wp_redirect( 'http://example.com/foo' );
exit();
}
//match $requested_url against your path pattern
//and return the url you want the user to be redirected to
return 'http://example.com/foo';
}
return $redirect_url;
}
add_filter( 'redirect_canonical', 'smarter_404s', 10, 2 );
add_action( 'template_redirect', 'smarter_404s' );
template\u redirect
不传递第二个参数,并且它不关心返回的值,因为它是一个动作挂钩。因此,如果需要,您可以通过给$requested\u url
一个默认值来使用相同的回调,但这将导致嵌套的if
块