Custom rewrite rules in Wordpress

前端 未结 1 1682
攒了一身酷
攒了一身酷 2021-01-16 18:07

I\'m in trouble with the internal wordpress rewrite rules. I\'ve read this thread but I still can\'t get any results: wp_rewrite in a WordPress Plugin

I explain my s

相关标签:
1条回答
  • 2021-01-16 18:33

    You'll need to add your own rewrite rule and query vars - pop this in functions.php;

    function my_rewrite_rules($rules)
    {
        global $wp_rewrite;
    
        // the slug of the page to handle these rules
        $my_page = 'mypage';
    
        // the key is a regular expression
        // the value maps matches into a query string
        $my_rule = array(
            'mypage/(.+)/(.+)/?' => 'index.php?pagename=' . $my_page . '&my_action=$matches[1]&my_show=$matches[2]'
        );
    
        return array_merge($my_rule, $rules);
    }
    add_filter('page_rewrite_rules', 'my_rewrite_rules');
    
    
    function my_query_vars($vars)
    {
        // these values should match those in the rewrite rule query string above
        // I recommend using something more unique than 'action' and 'show', as you
        // could collide with other plugins or WordPress core
        $my_vars = array(
            'my_action',
            'my_show'
        );
    
        return array_merge($my_vars, $vars);
    }
    add_filter('query_vars', 'my_query_vars');
    

    Now in your page template, replace $_GET[$var] with get_query_var($var) like so;

    <?php
    get_header();
    switch (get_query_var('my_action')) {
        case = "show" {
            echo esc_html(get_query_var('my_say')); // escape!
        }
    }
    get_footer();
    ?>
    
    0 讨论(0)
提交回复
热议问题