WordPress 공간에 잠시 동안 있었다면 아마도 WordPress REST API에 대해 들어본 적이 있을 것입니다. 조사를 해 본 적이 있다면 발견한 내용, 즉 많은 기술 전문 용어와 실제로 사용하는 방법에 대한 명확한 경로가 없는 것 때문에 정말 겁을 먹었을 것입니다.
오늘은 워드프레스 REST API를 사용하는 방법(완전 초보자)을 보여 드리겠습니다. 먼저 다른 WordPress 사이트에서 데이터를 가져오는 방법을 보여 드리겠습니다. 그런 다음 작동 방식을 확인한 후 몇 가지 핵심 용어를 소개하겠습니다.
시작하기 전에 Chrome을 열고 JSON 뷰어 확장 프로그램 을 설치합니다 . 아래 예제를 시도하면 출력이 훨씬 더 읽기 쉬운 형식으로 표시됩니다.
워드프레스 REST API 사용
WordPress REST API를 사용하려면 /wp-json/wp/v2/postsWordPress 사이트 URL 끝에 추가하기만 하면 됩니다. 이렇게 하면 게시물 목록(JSON 형식)이 제공됩니다. per_page반환되는 기본 게시물 수는 10이지만 인수 를 사용하여 더 많거나 적게 표시하도록 선택할 수 있습니다 . 이에 대해서는 아래에서 설명하겠습니다.
예를 들어 https://renemorozowich.com/wp-json/wp/v2/posts 를 방문하십시오 . 훌륭해! 방금 WordPress REST API를 사용하여 내 최근 게시물 10개를 확인했습니다. 쉽죠?
특정 게시물을 반환하는 인수
특정 게시물을 얻기 위해 추가할 수 있는 몇 가지 인수 도 있습니다.
per_page반환할 결과 수를 지정할 수 있습니다. 여기에서 가장 최근의 두 블로그 게시물을 검색하고 있습니다. https://renemorozowich.com/wp-json/wp/v2/posts?per_page=2
order내림차순(기본값) 또는 오름차순으로 결과를 반환하는 방법을 지정할 수 있습니다. 여기에서 내 블로그 게시물을 오름차순으로 검색하고 있습니다. https://renemorozowich.com/wp-json/wp/v2/posts?order=asc
categories특정 카테고리의 게시물을 보여줍니다. /wp-json/wp/v2/categories( 메인 URL 끝에 추가하면 찾을 수 있는 ID를 알아야 합니다 .) 여기 기술 카테고리(ID 45)에서 게시물을 검색하고 있습니다. https://renemorozowich.com/wp- json/wp/v2/posts?카테고리=45
search특정 검색어가 포함된 게시물을 표시합니다. 여기에서 플러그인 이라는 단어에 대한 모든 게시물을 검색하고 있습니다 . https://renemorozowich.com/wp-json/wp/v2/posts?=search[plugin]
REST API를 사용한 예
인디애나에 있는 웹 디자인 회사인 Sumy Designs 에서 최근 두 개의 게시물을 가져오기 위해 약간의 플러그인을 작성했습니다 . 게시물 이름, 날짜 및 영구 링크가 반환됩니다.
출력은 다음과 같습니다.
작성자 웹사이트에 대해 알아야 할 사항 2022
년 9월 8일 Google Search Console 가이드: 2부 2022 년 9월 14일
며칠 후에 이 페이지를 다시 방문하면 게시물이 변경된 것을 볼 수 있습니다. REST API는 최신 게시물 2개를 가져오고 있으며, 이 게시물은 새 게시물을 게시할 때마다 변경됩니다.
코드는 다음과 같습니다.
<?php
/**
* Plugin Name: Get Posts via REST API
* Description: Gets the latest two posts from a blog via the REST API. Blog link, title and date included.
* Plugin URI: https://renemorozowich.com
* Author: Rene Morozowich
* Version: 1.0
* Text Domain: getpostsviarestapi
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.txt
*
* @package getpostsviarestapi
*/
// Disable direct file access.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Get posts via REST API.
*/
function get_posts_via_rest() {
// Initialize variable.
$allposts = '';
// Enter the name of your blog here followed by /wp-json/wp/v2/posts and add filters like this one that limits the result to 2 posts.
$response = wp_remote_get( 'https://www.sumydesigns.com/wp-json/wp/v2/posts?per_page=2' );
// Exit if error.
if ( is_wp_error( $response ) ) {
return;
}
// Get the body.
$posts = json_decode( wp_remote_retrieve_body( $response ) );
// Exit if nothing is returned.
if ( empty( $posts ) ) {
return;
}
// If there are posts.
if ( ! empty( $posts ) ) {
// For each post.
foreach ( $posts as $post ) {
// Use print_r($post); to get the details of the post and all available fields
// Format the date.
$fordate = date( 'n/j/Y', strtotime( $post->modified ) );
// Show a linked title and post date.
$allposts .= '<a href="' . esc_url( $post->link ) . '" target=\"_blank\">' . esc_html( $post->title->rendered ) . '</a> ' . esc_html( $fordate ) . '<br />';
}
return $allposts;
}
}
// Register as a shortcode to be used on the site.
add_shortcode( 'sc_get_posts_via_rest', 'get_posts_via_rest' );
구현하려면 코드를 저장하고 플러그인 폴더에 업로드하십시오. 그런 다음 게시물 또는 페이지에 단축 코드 [sc_get_posts_via_rest]를 추가합니다.
reference : https://renemorozowich.com/using-wordpress-rest-api-get-blogs/
'CMS > 워드프레스' 카테고리의 다른 글
워드프레스(WordPress) 쇼핑몰 솔루션 소개 (0) | 2022.04.28 |
---|
댓글