两个添加_重写_规则的最佳代码

时间:2012-07-09 作者:webmasters

我有两个自定义重写规则;在阅读了这里的大量优秀帖子后,我找到了一种让它们发挥作用的方法。

问题是:Is there a way to merge this code? I\'m not sure that the way I wrote it is optimal:

在我的功能中。php我有第一条规则的代码:

add_action(\'init\', \'rewrite_cat\'); // Rewrite Category
    add_action(\'query_vars\', \'rewrite_query_vars_cat\'); 
    add_filter(\'template_include\', \'rewrite_template_include_cat\'); 
    function rewrite_cat(){ 
        add_rewrite_rule( \'([^/]+)/([0-9]+)/?\', \'index.php?catname=$matches[1]&currentpage=$matches[2]\', \'top\' );
    }
    function rewrite_query_vars_cat($query_vars){    
        $query_vars[] = \'currentpage\'; 
        $query_vars[] = \'catname\'; 
        return $query_vars; 
        } 
    function rewrite_template_include_cat($template){     
        if (get_query_var(\'currentpage\') || get_query_var(\'catname\')){        
            $template = locate_template(array(\'category.php\'));
        }     
            return $template; 
        }
之后,这是第二条规则的代码:

add_action(\'init\', \'rewrite_perf\'); // Rewrite Perf
    add_action(\'query_vars\', \'rewrite_query_vars_perf\'); 
    add_filter(\'template_include\', \'rewrite_template_include_perf\'); 
    function rewrite_perf(){ 
        add_rewrite_rule(\'cam/([^/]+)/([^/]+)/?\', \'index.php?name=cam&sgcatname=$matches[1]&perf=$matches[2]\', \'top\');
    }
    function rewrite_query_vars_perf($query_vars){  
        $query_vars[] = \'sgcatname\'; 
        $query_vars[] = \'perf\'; 
        return $query_vars; 
        } 
    function rewrite_template_include_perf($template){     
        if (get_query_var(\'sgcatname\') || get_query_var(\'perf\')){        
            $template_perf = locate_template(array(\'single.php\'));
        }     
            return $template; 
        }       

1 个回复
最合适的回答,由SO网友:webmasters 整理而成

这是工作代码:

add_action(\'init\', \'rewrite_init\'); // Rewrite
    add_action(\'query_vars\', \'rewrite_query_vars\'); 
    add_filter(\'template_include\', \'rewrite_template_include\'); 
    function rewrite_init(){ 
        add_rewrite_rule(\'([^/]+)/([0-9]+)/?$\', \'index.php?catname=$matches[1]&currentpage=$matches[2]\', \'top\');
        add_rewrite_rule(\'cam/([^/]+)/?$\', \'index.php?name=cam&perf=$matches[1]\', \'top\');
    }
    function rewrite_query_vars($query_vars){    
        $query_vars[] = \'currentpage\'; 
        $query_vars[] = \'catname\'; 
        $query_vars[] = \'perf\'; 
        return $query_vars; 
    } 
    function rewrite_template_include($template){     
        if(get_query_var(\'currentpage\') || get_query_var(\'catname\')){        
            $template = locate_template(array(\'category.php\'));
        } elseif(get_query_var(\'perf\')){
            $template = locate_template(array(\'single.php\'));
        }
            return $template; 
    }

结束

相关推荐