【问题标题】:pass variable through url in wordpress在wordpress中通过url传递变量
【发布时间】:2017-03-27 17:22:23
【问题描述】:

我有 wordpress 自定义模板页面 test.php,我想在其中通过 url 传递变量,

http://localhost/wordpress/test?date=2017&postid=11&title=some-title

以这种格式,

http://localhost/wordpress/test/2017/11/some-title

并从 url 中获取参数。

我已关注此link,但无法产生我想要的结果。

还有其他方法可以达到我提到的预期结果吗???我是 wordpress 主题开发的新手。

【问题讨论】:

  • 会对“为什么”感兴趣。鉴于我对 WP 有一些经验,并且根本不需要这样做。当然,您可能有原因,或者您可能错过了实现最终结果的更简单方法。
  • 您可以使用您的 Web 服务器(apache 或 nginx)重写规则来重写查询参数的路径。这样用户将看到第二种格式,但在 php 中,您将使用第一种格式和查询参数,并使用 wordpress 中的普通 get_query_var

标签: php wordpress wordpress-theming


【解决方案1】:

好吧,正如@vl4d1m1r4 所建议的,我使用了网络服务器(在我的例子中是 apache)重写规则来重写路径。一些我已经达到了预期的结果。 在function.php中 我编写了以下代码来更新 wordpress(.htaccess) 中的重写规则

add_filter( 'query_vars', 'add_custom_query_vars' );
function add_custom_query_vars( $vars )
{
    array_push($vars, "test_year", "test_postid", "test_title");
    return $vars;
}
function custom_rewrite_rule()
{
    add_rewrite_rule('^test/([^/]*)/([^/]*)/([^/]*)?','index.php?pagename=test&test_year=$matches[1]&test_postid=$matches[2]&test_title=$matches[3]','top');
}
add_action('init', 'custom_rewrite_rule');

添加上述代码后,我已经重新保存了永久链接设置(设置>>永久链接)

获取自定义模板页面中的参数,即test.php。我使用了以下查询。

echo get_query_var('test_title');
echo get_query_var('test_postid');
echo get_query_var('test_year');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2016-02-02
    • 1970-01-01
    • 2011-11-03
    • 2012-09-30
    相关资源
    最近更新 更多