创建子页面的重写规则

时间:2017-09-25 作者:HelpNeeder

我想为每个URL子页面为“/团队”的页面添加一个动态页面。

如何配置“add\\u rewrite\\u rule”regex表达式以允许这样做?

示例:

path: http://page.com/business/team
rewrite: http://page.com/index.php?department-team=business

path: http://page.com/hr/team
rewrite: http://page.com/index.php?department-team=hr
我使用的代码:

add_action(\'query_vars\', \'department_team_add_query_vars\');
add_action(\'init\', \'department_team_add_rewrite_rules\');
add_filter(\'template_include\', \'department_team_template_include\');


function department_team_add_query_vars($vars)
{
    $vars[] = \'department-team\';

    return $vars;
}

function department_team_add_rewrite_rules()
{
    // do I need this?
    //add_rewrite_tag(\'%department-team%\', \'([^&]+)\');

    // rewrite url to
    add_rewrite_rule(
        \'/([^/]*)/team\',
        \'index.php?department-team=$matches[1]\',
        \'top\'
    );
}

function department_team_template_include($template)
{
    global $wp_query;
    $new_template = \'\';

    var_dump(array_key_exists(\'department-team\', $wp_query->query_vars));
    var_dump($wp_query->query_vars);

    if (array_key_exists(\'department-team\', $wp_query->query_vars)) {
        switch ($wp_query->query_vars[\'department-team\']) {
            case \'team\':
                $new_template = locate_template([\'department_team.php\']);

                break;
        }

        if ($new_template != \'\') {
            var_dump(\'aaa\');
            die();

            return $new_template;
        }
        else {
            $wp_query->set_404();

            status_header(404);

            return get_404_template();
        }
    }

    return $template;
}

2 个回复
SO网友:Milo

使用add_rewrite_endpoint 相反,它会为您生成规则。

add_rewrite_endpoint( \'team\', EP_PAGES );

SO网友:scytale

我也做过类似的事情。我有一个页面(country\\u tc),它使用一个自定义页面模板,可以动态生成请求国家的信息,也可以生成该国家的一系列子页面,例如。

/country/Egyptindex.php?pagename=国家和国家TC=埃及)

/country/egypt/safetyindex.php?pagename=国家和国家TC=埃及/安全)

我使用page_rewrite_rules 用于重新写入。我没有时间审查你的代码,所以我会这样做:

在站点功能中plugin:

//  allow WP to store querystring attribs for use in our pages
function tc_query_vars_filter($vars) {
  $vars[] = \'department-team\';
  $vars[] .= \'another-var\';
  return $vars;
}
add_filter( \'query_vars\', \'tc_query_vars_filter\' );

function tc_rewrite_rules($rules) {
   global $wp_rewrite;
   $tc_rule = array(
     // working example from my site
     \'country/(.+)/?\' => \'index.php?pagename=\' . \'country\' . \'&countrytc=$matches[1]\',
     // YOUR rule (not tested)
     \'/([^/]*)/team\', \'index.php?pagename=YOURPAGENAME&department-team=$matches[1]\'
   );
   return array_merge($tc_rule, $rules);
}
add_filter(\'page_rewrite_rules\', \'tc_rewrite_rules\');

AFTER ACTIVATING PLUGIN YOU NEED TO RE-SAVE PERMALINKS ON DASHBOARD - THIS WILL FLUSH/UPDATE YOUR REWRITE RULES

执行其余代码in your custom page 使用:

get_query_var(\'department-team\') - 根据需要清理、验证并执行您的包含。

结束

相关推荐