具有多个变量的复杂重写规则,其中一些相同

时间:2017-03-16 作者:andytela

我正在尝试为可筛选的基于成员的目录添加一些重写规则

例如,如果我有以下URL

www.example.com/members/location=gb/

www.example.com/members/location=gb/role=director/
我通常会这样做

$member_page_id = 123;
add_rewrite_rule( \'members/search/location =([^/]+)/?$\',
    \'index.php?page_id=\' . $member_page_id . \'&location=$matches[1]\',
    \'top\'
);
add_rewrite_rule( \'members/search/location =([^/]+)/role=([^/]+)/?$\',
    \'index.php?page_id=\' . $member_page_id . \'&location=$matches[1]&role=$matches[2]\',
    \'top\'
);
但是,如果我想有多个相同的变量,或者它们是按不同的顺序选择的,那么如何重写这些变量,比如:

www.example.com/members/location=gb/location=us/role=director/

www.example.com/members/location=gb/role=director/location=us/
我可能可以使用parse query对搜索字符串进行重新排序,因此总是说位置优先,然后是角色,这样就不会在同一个页面上有多个URL,但是当变量数量未知时,如何添加重写规则?

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

对于那些感兴趣的人,我通过以下方式绕过了它

add_rewrite_rule( \'members/search/(.+?)?$\',
    \'index.php?page_id=\' . $member_page_id . \'&search=$matches[1]\',
    \'top\'
);
因此,本质上是在搜索之后获取所有内容,然后进行处理,在解析查询时,我会像这样从“search”query\\u var解析查询

function wpse_set_pre_get_users( $query ){
    if( ! is_admin() ){

        $meta_query = $query->get( \'meta_query\' );
        $meta_new_query = array();

        if( get_query_var( \'search\' ) != \'\' ){
            $search_arr = explode( \'/\', get_query_var( \'search\' ) );

            foreach ( $search_arr as $search_val ) {
                $vals = explode( \'=\', $search_val );

                $serialize_value = serialize( strval( urldecode( $vals[ 0 ] ) ) );
                $meta_new_query = array(
                    array(
                        \'key\' => $vals[ 1 ],
                        \'value\' => trim( urldecode( $vals[ 0 ] ) ),
                        \'compare\' => \'=\',
                    ), 
                    array(
                        \'key\' => $vals[ 1 ],
                        \'value\' => trim( urldecode( $vals[ 0 ] ) ),
                        \'compare\' => \'LIKE\',
                    ), 
                    array(
                        \'key\' => $vals[ 1 ],
                        \'value\' => trim( $serialize_value ),
                        \'compare\' => \'LIKE\',
                    ), 
                    \'relation\' => \'OR\',
                );
                $meta_query = array_merge( $meta_query, array( $meta_new_query ) );
            }

            $query->set( \'meta_query\', $meta_query );
        }
    }
}

add_action( \'pre_get_users\',\'wpse_set_pre_get_users\' );

相关推荐