Home IT/WEB wordress rest api 에 featured image 경로 추가

wordress rest api 에 featured image 경로 추가

포스트에 featured image 를 추가하면 wordpress rest api 에는 featured_media 에 대한 id 만 응답받을 수 있다. 
이미지의 경로가 필요가 필요하여 추가적으로 넣어주었다. 이미지도 full 사이즈와 medium 사이즈가 따로 필요해서 각각 생성해주었다. 

아래 구문을 function.php 에 추가해주면 된다.
register_rest_field( array('portfolio') 에서 portfolio 에는 커스텀포스트타입 이름을 넣어주면 된다.
inline ad
add_action('rest_api_init', 'register_rest_images' );
function register_rest_images(){
    register_rest_field( array('portfolio'),
        'featured_image',
        array(
            'get_callback'    => 'get_rest_featured_image',
            'update_callback' => null,
            'schema'          => null,
        )
    );
    register_rest_field( array('portfolio'),
        'featured_thumbnail',
        array(
            'get_callback'    => 'get_rest_featured_medium_image',
            'update_callback' => null,
            'schema'          => null,
        )
    );
}

function get_rest_featured_image( $object, $field_name, $request ) {
    if( $object['featured_media'] ){
        $img = wp_get_attachment_image_src( $object['featured_media'], 'app-thumb' );
        return $img[0];
    }
    return false;
}

function get_rest_featured_medium_image( $object, $field_name, $request ) {
    if( $object['featured_media'] ){
        $img = wp_get_attachment_image_src( $object['featured_media'], 'medium' );
        return $img[0];
    }
    return false;
}

아래와 같은 결과를 확인하실 수 있습니다.

"featured_image": "https://markettraders.kr/wp-content/uploads/2021/03/photo-1604922824961-87cefb2e4b07.jpg",
"featured_thumbnail": "https://markettraders.kr/wp-content/uploads/2021/03/photo-1604922824961-87cefb2e4b07-512x512.jpg",

RECENT POSTS

[javascript]트리 구조의 객체를 재귀적 함수로 평면화하는 방법

const getItems = (items) => { const flattenItems = (currentItems) => { let flatItems = ; for...

[javascript]객체를 복사하고 특정 키를 제외하여 객체를 생성하는 방법

const obj = { name: 'markettraders', age: 20, address: { city: 'seoul', zip: '12345' ...

[javascript]!! 연산자 not not 연산자

"!!" 연산자는 값을 boolean으로 형변환하는 데 사용됩니다. 이를 "not not" 연산자라고도 합니다. 이 연산자는 값을 true 또는 false로 간단히 변환하여 반환합니다. 예를 들어, JavaScript에서 다음과...

Youtube 오디오 라이브러리에서 가장 많이 사용하는 음악 TOP20 을 알려드립니다.

YouTube 오디오 라이브러리는 콘텐츠 제작자가 저작권 침해에 대한 걱정 없이 동영상에 사용할 수 있는 방대하고 다양한 무료 음악 및 음향 효과 라이브러리입니다. 아래 URL...