请求解析在中处理WP::parse_request()
. 在那之后,有一个动作钩parse_request
这将为您提供wp
对象
我们假设http://www.example.com/my-custom-post-type/this-is-a-cool-article
是你的永久链接和http://www.example.com/mon-type-de-poste-personnalise/cest-un-article-sympa
最后是404。因此,首先要检查回调,如果wp
对象处于错误/404状态:
if ( ! empty( $wp->query_vars[ \'error\' ] && 404 == $wp->query_vars[ \'error\' ] ) {
//…
}
编辑:我犯了一个错误:不确定
$wp
别名URL上的状态始终为404。这在很大程度上取决于系统上的重写规则。因此,您需要直接检查别名cpt slug。
现在,您必须自己解析请求并查找元值以找到相应的帖子:
if ( ! empty( $wp->query_vars[ \'error\' ] && \'404\' == $wp->query_vars[ \'error\' ] ) {
//look up for your post, this var should looks like
// \'mon-type-de-poste-personnalise/cest-un-article-sympa\' in your case:
$wp->request;
//e.g.
$parts = explode( \'/\', $wp->request );
// your language slug
$slug = ( isset( $parts[ 1 ] ) ) ? $parts[ 1 ] : \'\';
// do your query with your meta value $slug here
}
接下来,要设置
$wp->query_vars
当我们面对最初的请求时,他们会是这样的:
if ( ! empty( $wp->query_vars[ \'error\' ] && \'404\' == $wp->query_vars[ \'error\' ] ) {
//look up for your post, this var should looks like
// \'mon-type-de-poste-personnalise/cest-un-article-sympa\' in your case:
$wp->request;
//e.g.
$parts = explode( \'/\', $wp->request );
// your i18n post slug
$slug = ( isset( $parts[ 1 ] ) ) ? $parts[ 1 ] : \'\';
// do your query with your meta value $slug here
// and setup the WP_Post object for the matching post
$matching_post; // WP_Post
// if you don\'t find any post, return here!
// unset the error flag
unset( $wp->query_vars[ \'error\' ] );
// your cpt slug
$cpt_slug = \'my-custom-post-type\';
$wp->query_vars[ $cpt_slug ] = $matching_post->post_name;
$wp->query_vars[ \'post_type\' ] = $cpt_slug;
$wp->query_vars[ \'name\' ] = $matching_post->post_name;
}
您必须做的最后一件事是通过删除函数来防止WordPress自动重定向到规范URL
redirect_canonical
从
template_redirect
措施:
if ( ! empty( $wp->query_vars[ \'error\' ] && \'404\' == $wp->query_vars[ \'error\' ] ) {
//look up for your post, this var should looks like
// \'mon-type-de-poste-personnalise/cest-un-article-sympa\' in your case:
$wp->request;
//e.g.
$parts = explode( \'/\', $wp->request );
// your language slug
$slug = ( isset( $parts[ 1 ] ) ) ? $parts[ 1 ] : \'\';
// do your query with your meta value $slug here
// and setup the WP_Post object for the matching post
$matching_post; // WP_Post
# unset the error flag
unset( $wp->query_vars[ \'error\' ] );
# your cpt slug
$cpt_slug = \'my-custom-post-type\';
$wp->query_vars[ $cpt_slug ] = $matching_post->post_name;
$wp->query_vars[ \'post_type\' ] = $cpt_slug;
$wp->query_vars[ \'name\' ] = $matching_post->post_name;
# don\'t redirect to the canonical url
remove_action( \'template_redirect\', \'redirect_canonical\' );
}
将最后一个代码块放入函数中,并将其应用于
parse_request
措施:
add_action( \'parse_request\', \'wpse_126309_parse_request\' );
/**
* @wp-hook parse_request
* @param WP $wp
* @return void
*/
function wpse_126309_parse_request( $wp ) {
// the code goes here
}
您应该测试这个示例的副作用(这只是概念验证)。