我如何在Word中创建$ P $的PSS的“路线”? [英] How do I create a 'route' in wordpress?

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

问题描述

有关我自己的理智,我试图创建一个AJAX API,看起来像一个路线:

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

/api/<action>

我想这个词preSS来处理这条路线,并委托与 do_action 适当的行动。是否字preSS给我一个钩子来实现这一点?哪里是一个好去处?

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

}

这将创建 /土族-照片/ MAS-votadas /土族-照片/ MAS-votadas /页/ {数} ,即改变排序依据查询VAR为一个自定义的,这是我在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.

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

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