WordPress 模板的 URL 重写规则?

问题描述 投票:0回答:1

我已经建立了房地产网站,具有相当典型的房产搜索功能,可以在房产搜索页面上返回房产列表。

当访问者点击搜索结果中的列表时,我需要将属性的 ID 传递到 WP 页面“property-detail”(调用名为 template-propertydetail.php 的模板),然后该页面使用该 ID从数据库中提取属性数据。

所以我需要的是一个点击的链接,例如:

https://example.com/property-detail/?mlsid=12345

页面显示时重写为:

https://example.com/property-detail/12345

更新 我已经在functions.php中实现了Moishy建议的代码,但url没有重写。

function custom_rewrite_rule() {
    add_rewrite_rule(
        '^property-detail/([^/]+)/?$',
        'index.php?template_page=property_detail&mlsid=$matches[1]',
        'top', 'top'
    );
}
add_action('init', 'custom_rewrite_rule');

function add_query_vars_filter( $vars ){
    $vars[] = "template_page";
    $vars[] = "mlsid";
    return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

function include_custom_template($template){
    if(get_query_var('template_page') && get_query_var('template_page') === 'property_detail'){
        $template = get_template_directory() ."/templates/template-propertydetail.php";
    }
    return $template;
}
add_filter('template_include', 'include_custom_template');
wordpress url-rewriting
1个回答
0
投票
function custom_rewrite_rule() {
    add_rewrite_rule(
        '^property-detail/([^/]+)/?$', 
        'index.php?template_page=property_detail&mlsid=$matches[1]', 'top',
        'top'
    );
}

add_action('init', 'custom_rewrite_rule');

function add_query_vars_filter( $vars ){
    $vars[] = "template_page";
    $vars[] = "mlsid";
  return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

然后就可以在模板页面拉取id了:

get_query_var('mlsid')

并提取您的自定义模板:

function include_custom_template($template){


    if(get_query_var('template_page') && get_query_var('template_page') === 'property_detail'){
        $template = get_template_directory() ."YOUR_TEMPLATE_FILE";
    }
    
    return $template;
      
}

add_filter('template_include', 'include_custom_template');

确保在添加规则后刷新缓存并重写规则,方法是转至“设置”>“永久链接”并点击“保存更改”

© www.soinside.com 2019 - 2024. All rights reserved.