如何在 WordPress 中创建“路线”?

2024-04-26

为了我自己的理智,我正在尝试为 ajax api 创建一条路由,如下所示:

/api/<action>

我希望 WordPress 能够处理这条路线并委托给正确的操作do_action。 wordpress 是否给我一个钩子来实现这个?哪里有好地方?


你必须使用添加重写规则 http://codex.wordpress.org/Rewrite_API/add_rewrite_rule

就像是:

add_action('init', 'theme_functionality_urls');

function theme_functionality_urls() {

  /* Order section by fb likes */
  add_rewrite_rule(
    '^tus-fotos/mas-votadas/page/(\d)?',
    'index.php?post_type=usercontent&orderby=fb_likes&paged=$matches[1]',
    'top'
  );
  add_rewrite_rule(
    '^tus-fotos/mas-votadas?',
    'index.php?post_type=usercontent&orderby=fb_likes',
    'top'
  );

}

这创造了/tus-fotos/mas-votadas and /tus-fotos/mas-votadas/page/{number},这会将 orderby 查询变量更改为自定义查询变量,我在 pre_get_posts 过滤器中处理该变量。

还可以使用以下命令添加新变量query_vars过滤器并将其添加到重写规则中。

add_filter('query_vars', 'custom_query_vars');
add_action('init', 'theme_functionality_urls');

function custom_query_vars($vars){
  $vars[] = 'api_action';
  return $vars;
}

function theme_functionality_urls() {

  add_rewrite_rule(
    '^api/(\w)?',
    'index.php?api_action=$matches[1]',
    'top'
  );

}

然后,处理自定义请求:

add_action('parse_request', 'custom_requests');
function custom_requests ( $wp ) { 

  $valid_actions = array('action1', 'action2');

  if(
    !empty($wp->query_vars['api_action']) &&
    in_array($wp->query_vars['api_action'], $valid_actions) 
  ) {

    // do something here

  }

}

只需记住通过访问刷新重写规则/wp-admin/options-permalink.php或致电刷新重写规则 http://codex.wordpress.org/flush_rewrite_rules 仅在需要时,因为这不是一个简单的过程。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 WordPress 中创建“路线”? 的相关文章

随机推荐