首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >URL重写参数丢失(add_rewrite_rule)

问URL重写参数丢失(add_rewrite_rule)
EN

WordPress Development用户
提问于 2022-09-30 08:50:57
回答 1查看 53关注 0票数 0

这绝对不是有关这个问题的第一个问题。我读了很多书,试过更多,但没有成功。

我想做以下工作:将URL从:example.com/car/lambo重写到:example.com/index.php?P=42& do;#>model=lambo

p参数对应于我创建的固定页ID。

我有一个定制插件,在这个插件中,我使用plugins_loaded钩子从我的CarUrlRewrite类加载方法setupFrontendRewrites。

这门课看起来是这样的:

代码语言:javascript
复制
class CarUrlRewrite{
    const regex = 'cars/(.+?)/?我做了一些error_log输出,以确保调用所有类方法。正在发生的是重写工作,因为它将我转发到页面(页ID 42)。然后,URL为example.com/myslug (其中myslug是页面中的permalink )。但是,没有模型参数。我需要的是example.com/myslug?model=lambo;
    const param = 'model';
    const pageId = 42;

    // this method is called with the plugins_loaded hook
    public static function setupFrontendRewrites(){ 
        add_action('wp_loaded', array(__CLASS__, 'flushRulesIfNecessary'));
        add_filter('query_vars', array(__CLASS__, 'addQueryVariables'));
        add_action('init', array(__CLASS__, 'rewriteRules'));
        add_action('template_redirect', array(__CLASS__, 'rewriteCatchesToInjectContent'));
    }

    public static function flushRulesIfNecessary(){
        $wpRewriteRules = get_option( 'rewrite_rules' );
        if (!isset($wpRewriteRules[self::regex])){ // if my regex is missing, flush rules!
            global $wp_rewrite;
            $wp_rewrite->flush_rules();
        }
    }

    public static function addQueryVariables($vars){
        $vars[] = self::param;
        return $vars; // this is a filter after all
    }

    public static function rewriteRules() {
        // from: example.com/cars/lambo
        // into: example.com/index.php?p=42&model=lambo
        add_rewrite_rule(
            self::regex,
            'index.php?p='.self::pageId.'&'.self::param.'=$matches[1]',
            'top'
        );
    }

    // Catch the URL and redirect it to a template file
    public static function rewriteCatchesToInjectContent() {
        global $wp_query; 
        $model = array_key_exists('model', $wp_query->query_vars) ? $wp_query->query_vars['model'] : null;
        // would expect to see the model parameter filled here, but don't :-(
        // do something with the model variable
    }
}

我做了一些D4输出,以确保调用所有类方法。

正在发生的是重写工作,因为它将我转发到页面(页ID 42)。然后,URL为example.com/myslug (其中myslug是页面中的permalink )。但是,没有模型参数。我需要的是example.com/myslug?model=lambo

EN

回答 1

WordPress Development用户

回答已采纳

发布于 2022-09-30 16:10:31

然后,URL为example.com/myslug (其中myslug是页面中的permalink )。但是,没有模型参数。

这是因为您对Page ID使用了错误的参数:

p参数对应于我创建的固定页ID。

因此,实际上,对于page post类型,即页面,您应该使用page_id而不是p。有关更多细节,请参见文档。

因此,您只需要用index.php?p=替换index.php?page_id=,重写规则就能正常工作,但请记住通过Permalink设置管理页面手动刷新重写规则。(只需访问页面,WordPress就可以自动刷新规则,而不必单击“保存更改”按钮)

票数 1
EN
页面原文内容由WordPress Development提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://wordpress.stackexchange.com/questions/410007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档