Home IT/WEB wordpress rest api 에 tag id 와 tag name 포함시키는 방법

wordpress rest api 에 tag id 와 tag name 포함시키는 방법

wordpress rest api 의 tags 값을 확인하면 아래와 같이 tag 의 id 값을 응답 받을 수 있다.
내가 원하는 형태는 tags : [{id : 11, name: markettraders},{id : 4, name: google}] 이런 형태를 원한다. 태그의 목록을 출력하고 싶은데 tag의 id 값 밖에 없어서 추가 설정이 필요로 한다.

inline ad
"tags": [
      11,
      4
],

아래의 포스트글에는 tag name 만 추가하는 방법을 알려준다.

function ag_filter_post_json($response, $post, $context) {
    $tags = wp_get_post_tags($post->ID);
    $response->data['tag_names'] = [];

    foreach ($tags as $tag) {
        $response->data['tag_names'][] = $tag->name;
    }

    return $response;
}

add_filter( 'rest_prepare_post', 'ag_filter_post_json', 10, 3 );

하지만 내가 원하는 형태는 id, name 이 포함되어 있는 형태여서 위의 구문을 참고하여 수정하였다.
커스텀 포스트타입의 경우 rest_prepare_post 를 rest_prepare_(custom post type name) 이런 형태로 커스텀 포스트 타입을 적어주면 된다.

add_filter( 'rest_prepare_post', 'ag_filter_post_json', 10, 3 );

function ag_filter_post_json($response, $post, $context) {
    $tags = wp_get_post_tags($post->ID);
    $response->data['tag'] = array();
    $array_tag = array();

    foreach ($tags as $tag) {
        $array_tag['name'] = $tag->name;
        $array_tag['id'] =  $tag->term_id;
        $response->data['tag'][] = $array_tag;
    }
    return $response;
}

위 구문을 function.php 에 입력하고 rest api 주소로 요청하면 아래와 같은 형태로 응답 받을 수 있다.

"tag": [
      {
        "name": "aaa",
        "id": 11
      },
      {
        "name": "bbb",
        "id": 4
      }
    ],

———————————————————————————————–
2021-03-08 추가

위의 구문 조금 변경하였습니다. 태그와 카테고리 텍소노미에 대해서 id, name 을 추가하였습니다.

// 포트폴리오 텍소노미(category, tags) rest api 추가
add_filter( 'rest_prepare_portfolio', 'portfolio_taxonomy_json', 10, 3 );
function portfolio_taxonomy_json($response, $post, $context)
{
    $tags = wp_get_post_terms($post->ID, 'portfolio_tag');
    $categories = wp_get_post_terms($post->ID, 'portfolio_category');

    $response->data['portfolio_tags'] = array();
    $response->data['portfolio_categories'] = array();
    $array_tag = array();
    $array_category = array();

    foreach ($tags as $tag) {
        $array_tag['name'] = $tag->name;
        $array_tag['id'] = $tag->term_id;
        $response->data['portfolio_tags'][] = $array_tag;
    }
    foreach ($categories as $category) {
        $array_category['name'] = $category->name;
        $array_category['id'] = $category->term_id;
        $response->data['portfolio_categories'][] = $array_category;
    }
    return $response;
}

RECENT POSTS

[vscode]이 시스템에서 스크립트를 실행할 수 없으므로 nest.ps1 파일을 로드할 수 없습니다.

nest : 이 시스템에서 스크립트를 실행할 수 없으므로 C:UsersmarkettradersAppDataRoamingnpmnest.ps1 파일을 로드할 수 없습니다. 자세한 내용은 about_Execution_Policies(https://go.microsoft.com/fwlink/?LinkID=135170)를 참조하십시오.위치 줄:1 문자:1 이 오류는 PowerShell 실행 정책 관련...

[nest.js]nest.js, node.js, 프로젝트 생성 방법

Node.js 설치 Node.js의 공식 웹사이트(nodejs.org)에서 Windows용 인스톨러를 다운로드합니다. 다운로드한 인스톨러를 실행하여 설치합니다. Node Version Manager(NVM)을 사용하는 경우 nvm install node # 최신 버전 설치 nvm install 14 #...

[광주]위파크 더 센트럴 분양주택 분양안내

기본정보 공급위치: 광주광역시 서구 풍암동 10-12번지 일원 공급번호: 2023000351 공급규모: 625세대 분양/입주: 분양 2023-08-04 / 입주 2026-08 건설사: (주)호반건설 (주)라인건설 분양문의: 1670-5676 분양정보: 분양정보 자세히보기 홈페이지 주소: http://www.wepark-central.co.kr/ 모집공고문 보기 청약일정 모집공고일: 2023-08-04 청약접수: 2023-08-14...

[강원]힐스테이트 속초 분양주택 분양안내

기본정보 공급위치: 강원특별자치도 속초시 금호동 622-40 일원 공급번호: 2023000337 공급규모: 925세대 분양/입주: 분양 2023-07-21 / 입주 2026-05 건설사: 현대엔지니어링(주) 분양문의: 033-947-0925 분양정보: 분양정보 자세히보기 홈페이지 주소: http://www.hillstate-sokcho.co.kr 모집공고문 보기 청약일정 모집공고일: 2023-07-21 청약접수: 2023-07-31 ~...