web-dev-qa-db-ja.com

APIのカテゴリとタグを使用して投稿の選択クエリを実行する方法

カテゴリとタグを使って複数の投稿を取得したいです。実際、私は自分のWordpressサイト用のAPIを作成しています。完全なコードは次のようになります。

 $mysql = mysqli_query($con,"SELECT p.post_title,
       p.ID,
       p.post_content,
       p.post_date,
       p.post_name as url,
       t.name as category_name
FROM wp_posts p,
     wp_terms t,
     wp_term_relationships r,
     wp_term_taxonomy tt
WHERE p.post_status='publish' AND
      tt.taxonomy = 'post_tag' AND
      p.id=r.object_id AND
      r.term_taxonomy_id=tt.term_taxonomy_id AND
      tt.term_id = t.term_id order by p.post_date desc limit ".(int)($pageNumber*$pageSize).",".(int)$pageSize."") or die ("error".mysqli_error($con));
   $count = mysqli_num_rows($mysql);

MySQLi接続は機能します。しかし、このコードを実行すると、空白のページしか表示されません。どうすればこれを修正できますか?

1
M GR

WordPressにはすでに拡張可能なAPIと投稿を照会するためのクラスがあります。

例えば:

// when the rest_api_init action/event happens
add_action( 'rest_api_init', function () {
  // register a new endpoint
  register_rest_route( 'mohnish/v1', '/posts/', array(
    'methods' => 'GET',
    'callback' => 'mohnish_awesome_func', // that calls this function
  ) );
} );

// this is whats called when something hits the endpoint
function mohnish_awesome_func( WP_REST_Request $request ) {
    // grab the parameters
    $category = $request->get_param( 'category' );
    $tag = $request->get_param( 'tag' );

    // run the query to fetch the data
    $q = new WP_Query( [
        'category_name' => $category,
        'tag' => $tag,
        // etc...
    ]);
    $results = []; // an empty array to hold our results

    if ( $q->have_posts() ) {
        while( $q->have_posts() ) {
            $q->the_post();
            // add a new result to the list
            $results[] = [
                'title' => get_the_title(),
                // etc...
            ];
        }
    }

    return $results; // the REST API will automagically convert this to json
}

これにより、次のようなURLを書くことができます。

https://example.com/wp-json/mohnish/v1/posts/?category=foo&tag=bar

そして、JSONデータ構造を情報とともに返します。

幸いなことに、Coreには既に/wp-json/wp/v2/postsでやりたいことの多くを行うポストエンドポイントがあります。これはライブサイトの例です。

curl http://demo.wp-api.org/wp-json/wp/v2/posts

ここで返される内容のフルスキーマと例 投稿の削除と個々の投稿の取得、および すべての機能の使用方法を説明したハンドブック そしてそれを拡張

1
Tom J Nowell