在WordPress中,我在ajax中设置了如下查询参数
add_action( \'wp_ajax_get_prepare_link\', \'prepare_link\');
add_action( \'wp_ajax_nopriv_get_prepare_link\', \'prepare_link\');
function prepare_link() {
//Do some logic and get the models name
$url = add_query_arg( array(
\'compare\' => aaa-and-bbb-and-ccc,
), \'http://example.com/cars/\' );
echo $url;
wp_die();
}
所以在这之后,我得到了如下url
http://example.com/cars/?compare=aaa-and-bbb-and-ccc
因此,我在jQuery中将页面重定向到响应url,如下所示
jQuery(\'a.compare-vechicles\').click(function(e){
jQuery.ajax({
type: "POST",
url: script.ajax_url,
data: {
action : \'get_prepare_link\',
},
success: function(data){
window.location = data; //Redirect to the prepared link
}
});
});
现在我想让它成为seo友好的url。所以输出url应该如下所示
http://example.com/cars/compare/aaa-and-bbb-and-ccc
所以为了达到这个目的,我做了这样的
add_action(\'init\', \'custom_rewrite_basic\' );
function custom_rewrite_basic() {
add_rewrite_rule(\'^compare/([^/]*)/?\',
\'index.php?pagename=$matches[1]\',
\'top\');
}
但它根本不起作用。那么有人能告诉我怎样才能做到这一点吗?
谢谢
SO网友:Milan Hirpara
此add\\u query\\u arg函数是输入URL后的add参数。
您必须获得漂亮的URL,所以在函数中添加以下代码。php文件:
function custom_rewrite_rule() {
add_rewrite_rule(\'^cars/([^/]*)/([^/]*)/?\',\'index.php?page_id=PAGE_ID&type=$matches[1]&models=$matches[2]\',\'top\');
flush_rewrite_rules();
}
add_action(\'init\', \'custom_rewrite_rule\', 10, 0);
function custom_rewrite_tag() {
add_rewrite_tag(\'%type%\', \'([^&]+)\');
add_rewrite_tag(\'%models%\', \'([^&]+)\');
}
add_action(\'init\', \'custom_rewrite_tag\', 10, 0);
add_action( \'wp_ajax_get_prepare_link\', \'prepare_link\');
add_action( \'wp_ajax_nopriv_get_prepare_link\', \'prepare_link\');
function prepare_link() {
$url = "";
$url .= get_the_permalink( PAGE_ID );
$url .= "compare/aaa-and-bbb-and-ccc"
echo $url;
wp_die();
}
In above code replace "PAGE_ID" with your "car" page id.