如果您还没有这样做,我建议您退房this Codex article 这很好地介绍了如何使用add_rewrite_rule() 在WordPress中重写URL。
现在如果news 和single 是页面(即page 类型)和single 是news 第页,然后在第二个参数中add_rewrite_rule() (即重定向URL),您希望使用pagename=news/single 将加载single 页
或者,您可以使用page_id=<ID> 改为按其ID查询页面。
请参见WP_Query class 有关pagename 和page_id.
然后,您还需要为单个新闻ID使用自定义查询参数,因为例如,您无法使用$_GET[\'id\']. 然后您应该将自定义参数添加到WordPress从URL读取并将其传递给的公共查询参数中WP_Query.
话虽如此,请尝试以下方法:
// Register the custom rewrite rule.
function wpse_373628_init() {
add_rewrite_rule(
// Matches /news/<id>/<title-slug> in the URL.
\'^news/(\\d+)/([^/]+)/?$\',
// You could also add &news_title=$matches[2], but I think the ID is
// enough for you to identify the single news being requested.
\'index.php?pagename=news/single&news_id=$matches[1]\', // query by slug
// \'index.php?page_id=123&news_id=$matches[1]\', // or query by ID
\'top\'
);
}
add_action( \'init\', \'wpse_373628_init\' );
// And register the custom query arg.
function wpse_373628_query_vars( $vars ) {
$vars[] = \'news_id\';
// $vars[] = \'news_title\'; // if you\'re using news_title in the rewrite rule
return $vars;
}
add_filter( \'query_vars\', \'wpse_373628_query_vars\' );
只需访问permalink设置页面,即可刷新重写规则(
wp-admin »永久链接设置),以便WordPress识别新的重写规则(如上)并将其保存在数据库中。
此外,要检索新闻ID,可以使用get_query_var( \'news_id\' ).