我正在为我的个人网站开发一个插件,我希望它具有一定的永久链接结构(/项目/项目类型/子类型/项目)。为了实现这一点,我使用request
滤器
在我的hook方法中,我正在检查以确保在加载post类型(project)之前分类(y | ies)(project\\u type)存在。如果没有,过滤器将抛出404错误并加载主题的错误模板,而不是仅显示项目。这样做安全吗?
public function request( $request ) {
$dummy_query = new \\WP_Query();
$dummy_query->parse_query( $request );
if ( ! $dummy_query->is_admin && isset( $request[\'project_type\'] ) ) {
$last_segment = basename( $request[\'project_type\'] );
if ( false === get_term_by( \'slug\', $last_segment, \'project_type\' ) ) {
$types = explode( \'/\', substr( $request[\'project_type\'], 0, strrpos( $request[\'project_type\'], \'/\' ) ) );
foreach( $types as $type ) {
if ( false === get_term_by( \'slug\', $type, \'project_type\' ) ) {
header( \'HTTP/1.0 404 Not Found\' );
locate_template( array( \'404.php\' ), true, true );
exit;
}
}
$request[\'post_type\'] = \'project\';
$request[\'project\'] = $last_segment;
$request[\'name\'] = $last_segment;
}
}
return $request;
}
此代码修改自
this answer.