如何在 wordpress 中创建“路线"? [英] How do I create a 'route' in wordpress?

查看:19
本文介绍了如何在 wordpress 中创建“路线"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For my own sanity I'm trying to create a route for an ajax api that looks something like:

/api/<action>

我希望 wordpress 处理这条路线,并使用 do_action 委托给适当的操作.wordpress 会给我一个钩子来实现这个吗?哪里有好去处?

I'd like wordpress to handle this route and delegate to the proper action with do_action. Does wordpress give me a hook to implement this? Where's a good spot?

推荐答案

你必须使用 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/tus-fotos/mas-votadas/page/{number},改变 orderby 查询变量一个自定义的,我在 pre_get_posts 过滤器中处理.

This creates /tus-fotos/mas-votadas and /tus-fotos/mas-votadas/page/{number}, that changes the orderby query var for a custom one, which I handle in the pre_get_posts filter.

也可以使用 query_vars 过滤器添加新变量并将其添加到重写规则中.

New variables can also be added using the query_vars filters and adding it to the rewrite rule.

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'
  );

}

然后,处理自定义请求:

Then, handle the custom request:

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 或调用 flush_rewrite_rules 仅在需要时使用,因为这不是一个微不足道的过程.

Just remember to flush the rewrite rules by visiting /wp-admin/options-permalink.php or calling flush_rewrite_rules only when needed, since it's not a trivial process.

这篇关于如何在 wordpress 中创建“路线"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆