WordPressgenerate_rewrite_rules没有特定的slug

发布于 2025-01-12 18:31:12 字数 925 浏览 0 评论 0原文

目标:我需要在 WordPress 上生成自定义 URL 以将 slug 转换为变量。斜杠后面的任何内容都将被视为水果的名称。

例如,要生产香蕉,我需要去 website.com/u/banana

我的预期:website.com/banana

问题: 我需要删除该 '/u /' 部分,并防止与其他标准页面 slug 发生任何可能的冲突。

我的代码:

add_filter( 'generate_rewrite_rules', function ( $wp_rewrite ){
    $wp_rewrite->rules = array_merge(
        ['u/([^/]*)' => 'index.php?fruit=$matches[1]'],
        $wp_rewrite->rules
    );
} );

add_filter( 'query_vars', function( $query_vars ){ 
    $query_vars[] = 'fruit';
    return $query_vars;
} );

add_filter( 'home_template', 'wpa3396_page_template' );
function wpa3396_page_template( $page_template )
{
    if ( get_query_var( 'fruit' ) ) :
      $page_template = plugin_dir_path( __FILE__ ) . 'templates/fruitcase.php';
      return $page_template;
    endif;
}

Goal : I need to generate custom URL on WordPress to convert the slug into variable. Anything after slash will be considered as fruit's name.

For example, to produce banana, I need to go to
website.com/u/banana

What I expected : website.com/banana

Problem : I need to remove that '/u/' part from the URL and prevent any possible conflict with other standard pages slug.

My code :

add_filter( 'generate_rewrite_rules', function ( $wp_rewrite ){
    $wp_rewrite->rules = array_merge(
        ['u/([^/]*)' => 'index.php?fruit=$matches[1]'],
        $wp_rewrite->rules
    );
} );

add_filter( 'query_vars', function( $query_vars ){ 
    $query_vars[] = 'fruit';
    return $query_vars;
} );

add_filter( 'home_template', 'wpa3396_page_template' );
function wpa3396_page_template( $page_template )
{
    if ( get_query_var( 'fruit' ) ) :
      $page_template = plugin_dir_path( __FILE__ ) . 'templates/fruitcase.php';
      return $page_template;
    endif;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文