14

私自身の正気のために、次のような ajax API のルートを作成しようとしています。

/api/<action>

wordpress でこのルートを処理し、適切なアクションに委任したいと思いdo_actionます。ワードプレスはこれを実装するためのフックを提供してくれますか? いいところはどこ?

4

2 に答える 2

17

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 フィルターで処理します。

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

  }

}

単純なプロセスではないため、必要な場合にのみflush_rewrite_rules/wp-admin/options-permalink.phpにアクセスまたは呼び出して、書き換えルールをフラッシュすることを忘れないでください。

于 2013-05-31T18:46:56.330 に答える
1

wordpress json-apiプラグインを探しているようです。これは、私が使用したうまく構築されたプラグインの 1 つで、非常に簡単に拡張できます。頑張ってください。

于 2013-05-31T18:00:43.877 に答える