代码之家  ›  专栏  ›  技术社区  ›  Luke Stevenson

构建一个页面来使用URL从restapi中提取数据

  •  1
  • Luke Stevenson  · 技术社区  · 8 年前

    我希望能够有我的Wordpress站点的一部分,在那里我可以解析URL,然后使用这些值来填充来自另一个API的内容。

    例如:

    server.zz/weather/Sydney%20澳大利亚

    服务器:zz/weather/Houston%20Texas

    在这里我可以编写一个插件来拦截这些请求,能够提取url的结尾,然后调用另一个API来获取数据,然后合并到一个模板中呈现给访问者。

    如我所说,任何建议或建议将不胜感激。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Luke Stevenson    8 年前

    我用 add_rewrite_rule() , add_rewrite_endpoint() flush_rewrite_rule()

    对于我前面提供的示例,我在一个插件中创建了以下代码。

    // Define the URL Rewrite Rules
    function crw_rewrite_urls(){
      add_rewrite_rule(
        '^weather/(.+)$' ,
        'index.php?weather_location=$matches[1]' ,
        'top'
      );
      add_rewrite_endpoint('weather_location', EP_ROOT);
      flush_rewrite_rules();
    }
    add_action('init', 'crw_rewrite_urls');
    
    // Initialise the Query Variable
    function crw_query_var( $vars ) {
      $vars[] = 'weather_location';
      return $vars;
    }
    
    // Check for the Variable and Display Content as needed
    function crw_handler() {
      global $wp_query;
      if ( isset( $wp_query->query_vars['weather_location'] ) ) {
        // Call the API, fill the Template here
      }
      return;
    }
    add_action('template_redirect', 'crw_handler');