使用‘[’‘]’或‘(’‘)’作为文本重写URL

时间:2012-01-21 作者:Arnold Bailey

正在尝试像这样匹配和URL

linktosite/alphaNum/123/321/alphanum[alphanum].jpg
在中。htaccess我可以正确匹配和提取所有组

linktosite/(.+)/([0-9]+)/([0-9]+)/(.+)\\\\[(.+)\\\\]\\\\.(.+)$
在add\\u rewrite\\u规则中,我无法使其匹配。我试着逃离[ 具有\\\\[, \\\\\\\\[, \\\\\\\\\\\\\\\\[

什么都不管用。我也试过了\\Q[\\E 并将其用作\\x5b \\091 什么都不管用。也尝试过([^\\\\[]+) 匹配非[ 字符到[

这样匹配元字符的正确方法是什么??对文字执行相同的操作\\()

1 个回复
SO网友:Annika Backstrom

我发现这是WordPress文档记录最差的功能之一,所以希望这已经步入正轨,或者会被更熟练的WP\\U重写人员纠正。

因此,基本要点是:

在插件激活期间和刷新规则时,确保将自定义规则添加到列表中期间init, 使用add_rewrite_tag() 对于规则中的任何自定义查询字符串参数。目的地为index.php?this_is_custom=$matches[1], 您必须添加this_is_custom 标记

function wpse_39626_init() {
    // these must be added during init. if you haven\'t done
    // add_rewrite_tag() for all custom query string vars,
    // wordpress will ignore them.
    add_rewrite_tag( \'%wpse_thing%\', \'(\\w+)\' );
    add_rewrite_tag( \'%wpse_name%\', \'(\\w+)\' );
    add_rewrite_tag( \'%wpse_index%\', \'(\\w+)\' );

    // manually flushing rules so this code is easier to demo.
    // under normal circumstances you would use the plugin
    // activation hook. this will eventually call wpse_39626_rules().
    flush_rewrite_rules();
}
add_action( \'init\', \'wpse_39626_init\' );

// Normally, this would get called during something like
// your plugin\'s activation hook. See register_activation_hook().
function wpse_39626_activate() {
    add_rewrite_rule( \'testing/(\\w+)\\[(\\w+)\\]\', \'index.php?wpse_thing=custom&wpse_name=$matches[1]&wpse_index=$matches[2]\', \'top\' );
    flush_rewrite_rules();
}
//register_activation_hook( __FILE__, \'wpse_39626_activate\' );

// Hook into rewrite_rules_array, in case rewrite rules
// are flushed after the plugin is activated.
function wpse_39626_rules( $rules ) {
    $new_rules = array();

    // Matches: testing/outer[inner]
    //   wpse_name  = outer
    //   wpse_index = inner
    $new_rules[\'testing/(\\w+)\\[(\\w+)\\]\'] = \'index.php?wpse_thing=custom&wpse_name=$matches[1]&wpse_index=$matches[2]\';

    // prepend and return rules
    return $new_rules + $rules;
}
add_action( \'rewrite_rules_array\', \'wpse_39626_rules\' );

// Here\'s some demo code to intercept the page load
// and do custom functionality when our rewrite rule
// matches. (We\'ll just dump the matched values.)
function wpse_39626_posts( $query ) {
    if( ! is_main_query( $query ) ) {
        return;
    }

    if( $query->get(\'wpse_thing\') != \'custom\' ) {
        return;
    }

    var_dump( $query->get(\'wpse_name\') );
    var_dump( $query->get(\'wpse_index\') );

    die;
}
add_action( \'pre_get_posts\', \'wpse_39626_posts\' );
您的示例对代码有一点了解,尤其是在您试图匹配的URL中(所有这些参数对应的是什么?),所以我的回答有点笼统。

结束

相关推荐

GET_SHORTCODE_regex()只与第一个短码匹配

法典中有an example 使用get\\u shortcode\\u regex()检查是否在给定页面上调用了短代码:$pattern = get_shortcode_regex(); preg_match(\'/\'.$pattern.\'/s\', $posts[0]->post_content, $matches); if (is_array($matches) && $matches[2] == \'YOURSHORTCODE\') { /