LoginSignup
0
0

More than 1 year has passed since last update.

WordPress | WP REST API | "rendered"うざい

Last updated at Posted at 2021-09-10

"rendered" いらない

WordPressのAPIは便利ですが・・・

"title":{
  "rendered": "記事タイトル"
}

postData.title[0] とか postData.title["rendered"] とか
付けないと取得できない。これ地味にめんどい。

functions.php に追記

function X()
{
    register_rest_route(
                        'custom/v0',
                        '/posts',
                        [
                            'methods' => WP_REST_SERVER::READABLE,
                            'callback' => 'Y'
                        ]);
}

add_action('rest_api_init', 'X');


function Y()
{
    $_RESULT_ = [];

    $_POSTS_ = get_posts([
                    'post_type' => 'post',
                    'posts_per_page' => -1,
                    'order' => 'DESC'
                  ]);

    if ( $_POSTS_ ) {

        foreach ( $_POSTS_ as $_P_ ) {

            $ID = $_P_ -> ID;

            $DATE = mysql2date('Y/n/j', $_P_ -> post_date);

            $TITLE = $_P_ -> post_title;

            $_KEY_ = [
                  'id' => $ID,
                  'date' => $DATE,
                  'title' => $TITLE
                 ];

            array_push( $_RESULT_, $_KEY_ );
        }

    }
    return $_RESULT_;

}

これで、独自のURLができます。
http://localhost:8080/wp-json/custom/v0/posts

参考リンク

https://knowledge.cpi.ad.jp/cms/wp-rest-api2/
https://notes.sharesl.net/articles/751/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0