프론트 엔드 PlatoBlockchain 데이터 인텔리전스에서 WordPress 블록의 외부 API 데이터 렌더링. 수직 검색. 일체 포함.

프런트 엔드의 WordPress 블록에서 외부 API 데이터 렌더링

WordPress 블록 작업을 위한 CSS-Tricks에 대한 몇 가지 새로운 자습서가 여기에 나타납니다. 그들 중 하나 는 WordPress 블록 개발에 대한 소개이며 블록이 무엇인지 배우고 페이지 및 게시물에서 사용하기 위해 WordPress에 등록하기에 좋은 곳입니다.

블록 기본 사항은 해당 게시물에서 잘 다루지만, 저는 한 단계 더 나아가고 싶습니다. 그 기사에서 우리는 백엔드 WordPress 블록 편집기에서 블록을 렌더링하는 것과 프런트 엔드 테마에서 렌더링하는 것의 차이점을 배웠습니다. 예제는 각 끝에 다른 콘텐츠와 스타일을 렌더링하는 간단한 Pullquote 블록이었습니다.

더 나아가 사용법을 살펴보자. 동적 컨텐츠 WordPress 블록에서. 보다 구체적으로, 외부 API에서 데이터를 가져와서 특정 블록이 블록 편집기에 드롭될 때 프런트 엔드에서 렌더링해 보겠습니다.

축구(어, 축구)에서 가져온 순위 아피풋볼.

이것이 우리가 함께 노력하는 것입니다.

API를 WordPress 블록과 통합하는 방법은 여러 가지가 있습니다! 블록 기초에 대한 기사는 이미 블록을 처음부터 만드는 과정을 거쳤기 때문에 우리는 다음을 사용하여 일을 단순화할 것입니다. @wordpress/create-block 패키지를 사용하여 작업을 부트스트랩하고 프로젝트를 구성합니다.

블록 플러그인 초기화

가장 먼저 할 일: 명령줄에서 새 프로젝트를 시작하겠습니다.

npx @wordpress/create-block football-rankings

나는 일반적으로 파일을 처음부터 만들어 이와 같은 프로젝트를 시작하지만 이 편리한 유틸리티에 대해 WordPress Core 팀에 찬사를 보냅니다!

명령으로 프로젝트 폴더가 생성되면 기술적으로 모든 기능을 갖춘 WordPress 블록이 플러그인으로 등록됩니다. 이제 프로젝트 폴더를 wp-content/plugins WordPress가 설치된 디렉토리(로컬 환경에서 작업하는 것이 가장 좋습니다)로 이동한 다음 WordPress 관리자에 로그인하여 플러그인 화면에서 활성화합니다.

프론트 엔드 PlatoBlockchain 데이터 인텔리전스에서 WordPress 블록의 외부 API 데이터 렌더링. 수직 검색. 일체 포함.
프런트 엔드의 WordPress 블록에서 외부 API 데이터 렌더링

이제 블록이 초기화, 설치 및 활성화되었으므로 다음 위치에서 프로젝트 폴더를 엽니다. /wp-content/plugins/football-rankings. 당신은 원할거야 cd 개발을 계속할 수 있도록 명령줄에서도 확인할 수 있습니다.

현재 집중해야 할 파일은 다음과 같습니다.

  • edit.js
  • index.js
  • football-rankings.php

프로젝트의 다른 파일은 물론 중요하지만 이 시점에서는 중요하지 않습니다.

API 소스 검토

우리는 이미 우리가 사용하고 있다는 것을 알고 있습니다. 아피풋볼 우리에게 호의를 베푸는 RapidAPI. 다행히 RapidAPI에는 2021년 프리미어 리그 순위에 대한 API 데이터를 가져오는 데 필요한 스크립트를 자동으로 생성하는 대시보드가 ​​있습니다.

API 소스의 코드와 데이터를 보여주는 XNUMX개의 열이 있는 대시보드 인터페이스.
RapidAPI 대시보드

JSON 구조를 살펴보고 싶다면 다음을 사용하여 시각적 표현을 생성할 수 있습니다. JSON크랙.

에서 데이터 가져오기 edit.js 파일

RapidAPI 코드를 내부에 래핑할 것입니다. 반응 useEffect() 페이지가 로드될 때 한 번만 실행되도록 빈 종속성 배열을 사용합니다. 이렇게 하면 블록 편집기가 다시 렌더링될 때마다 WordPress가 API를 호출하는 것을 방지할 수 있습니다. 를 사용하여 확인할 수 있습니다. wp.data.subscribe() 당신이 신경을 쓴다면.

가져오는 코드는 다음과 같습니다. useEffect(), 다음 주위를 감싸 fetch() RapidAPI가 제공한 코드:

/**
* The edit function describes the structure of your block in the context of the
* editor. This represents what the editor will render when the block is used.
*
* @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#edit
*
* @return {WPElement} Element to render.
*/

import { useEffect } from "@wordpress/element";

export default function Edit(props) {
  const { attributes, setAttributes } = props;

  useEffect(() => {
    const options = {
      method: "GET",
      headers: {
        "X-RapidAPI-Key": "Your Rapid API key",
        "X-RapidAPI-Host": "api-football-v1.p.rapidapi.com",
      },
    };

    fetch("https://api-football-v1.p.rapidapi.com/v3/standings?season=2021&league=39", options)
      .then( ( response ) => response.json() )
      .then( ( response ) => {
        let newData = { ...response };
        setAttributes( { data: newData } );
        console.log( "Attributes", attributes );
      })
      .catch((err) => console.error(err));
}, []);

  return (
    

{ __( "Standings loaded on the front end", "external-api-gutenberg" ) }

); }

내가 떠났다는 사실에 주목하라 return 기능은 거의 손상되지 않았지만 축구 순위가 프런트 엔드에서 렌더링되었음을 확인하는 메모가 포함되어 있습니다. 다시 말하지만, 이 기사에서는 프런트 엔드에만 초점을 맞출 것입니다. 블록 편집기에서도 데이터를 렌더링할 수 있지만 집중할 수 있도록 다른 기사에서 다루도록 하겠습니다.

WordPress에 API 데이터 저장

이제 데이터를 가져왔으므로 WordPress의 어딘가에 저장해야 합니다. 여기는 attributes.data 개체가 유용합니다. 우리는 정의하고 있습니다 data.typeobject 데이터를 가져오고 JSON으로 형식을 지정하기 때문입니다. 다른 유형이 없는지 확인하십시오. 그렇지 않으면 WordPress에서 데이터를 저장하지 않으며 디버그할 때 오류가 발생하지 않습니다.

우리는 이 모든 것을 우리의 index.js 파일 :

registerBlockType( metadata.name, {
  edit: Edit,
  attributes: {
    data: {
      type: "object",
    },
  },
  save,
} );

자, 이제 WordPress는 우리가 가져오는 RapidAPI 데이터가 객체라는 것을 알고 있습니다. WordPress 블록 편집기에서 새 게시물 초안을 열고 게시물을 저장하면 이제 데이터가 데이터베이스에 저장됩니다. 실제로 우리가 그것을 볼 수 있다면 wp_posts.post_content phpMyAdmin, Sequel Pro, Adminer 또는 사용하는 모든 도구에서 사이트의 데이터베이스를 여는 경우 필드입니다.

데이터베이스 테이블에 JSON 출력의 큰 문자열을 표시합니다.
WordPress 데이터베이스에 저장된 API 출력

프런트 엔드에서 JSON 데이터 출력

프런트 엔드에서 데이터를 출력하는 방법에는 여러 가지가 있습니다. 제가 보여드릴 방법은 데이터베이스에 저장된 속성을 가져와서 매개변수로 전달합니다. render_callback 우리의 기능 football-rankings.php 파일.

나는 관심사를 분리하는 것을 좋아하므로 블록 플러그인에 두 개의 새 파일을 추가합니다. build 폴더 : frontend.jsfrontend.css (당신은 만들 수 있습니다 frontend.scss 에 파일을 src CSS로 컴파일된 디렉토리 build 예배 규칙서). 이렇게 하면 백엔드 코드와 프론트엔드 코드가 분리되고 football-rankings.php 파일이 조금 더 읽기 쉽습니다.

/explanation 워드프레스 블록 개발 소개로 돌아가보면, editor.cssstyle.css 프론트 엔드와 백 엔드 사이의 백 엔드 및 공유 스타일에 대한 파일입니다. 추가하여 frontend.scss (로 컴파일 frontend.css, 프런트 엔드만을 위한 스타일을 분리할 수 있습니다.

새 파일에 대해 걱정하기 전에 다음과 같이 파일을 호출합니다. football-rankings.php:

/**
* Registers the block using the metadata loaded from the `block.json` file.
* Behind the scenes, it registers also all assets so they can be enqueued
* through the block editor in the corresponding context.
*
* @see https://developer.wordpress.org/reference/functions/register_block_type/
*/
function create_block_football_rankings_block_init() {
  register_block_type( __DIR__ . '/build', array(
    'render_callback' => 'render_frontend'
  ));
}
add_action( 'init', 'create_block_football_rankings_block_init' );

function render_frontend($attributes) {
  if( !is_admin() ) {
    wp_enqueue_script( 'football_rankings', plugin_dir_url( __FILE__ ) . '/build/frontend.js');
    wp_enqueue_style( 'football_rankings', plugin_dir_url( __FILE__ ) . '/build/frontend.css' ); // HIGHLIGHT 15,16,17,18
  }
  
  ob_start(); ?>

  
        
      

Rank
Team name
GP
GW
GD
GL
GF
GA
Pts
Last 5 games

<?php return ob_get_clean();
}

내가 사용하고 있기 때문에 render_callback() 속성에 대한 메서드, 블록 편집기 핸드북 제안. 에 포함되어 있는 !is_admin() 조건이며 편집기 화면을 사용하는 동안 대기열에 넣지 않도록 두 파일을 대기열에 추가합니다.

이제 호출하는 두 개의 새 파일이 있으므로 npm 그들을 컴파일합니다. 그래서, 그것을 할 package.json,에 scripts 섹션 :

"scripts": {
  "build": "wp-scripts build src/index.js src/frontend.js",
  "format": "wp-scripts format",
  "lint:css": "wp-scripts lint-style",
  "lint:js": "wp-scripts lint-js",
  "packages-update": "wp-scripts packages-update",
  "plugin-zip": "wp-scripts plugin-zip",
  "start": "wp-scripts start src/index.js src/frontend.js"
},

파일을 포함하는 또 다른 방법은 파일에 포함된 블록 메타데이터에 파일을 정의하는 것입니다. block.json 파일 언급 한 바와 같이 블록 개발 소개에서:

"viewScript": [ "file:./frontend.js", "example-shared-view-script" ],
"style": [ "file:./frontend.css", "example-shared-style" ],

내가 함께 가는 유일한 이유 package.json 방법은 이미 사용하고 있기 때문입니다. render_callback() 방법.

JSON 데이터 렌더링

렌더링 부분에서는 하나의 블록에만 집중하고 있습니다. 일반적으로 프론트 엔드에서 여러 블록을 대상으로 하고 싶을 것입니다. 그런 경우에는 다음을 활용해야 합니다. document.querySelectorAll() 블록의 특정 ID로

기본적으로 창에서 JSON에서 몇 가지 주요 개체에 대한 데이터를 로드하고 가져와 프런트 엔드에서 렌더링하는 일부 마크업에 적용할 때까지 기다립니다. 저도 환전하러 갑니다 attributes JavaScript를 통해 더 쉽게 읽을 수 있도록 데이터를 JSON 개체로 변환하고 축구 리그 로고, 팀 로고 및 통계와 같은 항목에 대해 JSON에서 HTML로 세부 정보를 설정합니다.

"최근 5경기" 열에는 팀의 최근 XNUMX경기 결과가 표시됩니다. API 데이터가 문자열 형식이므로 수동으로 데이터를 변경해야 합니다. 배열로 변환하면 HTML에서 팀의 마지막 XNUMX경기 각각에 대한 별도의 요소로 사용하는 데 도움이 될 수 있습니다.

import "./frontend.scss";

// Wait for the window to load
window.addEventListener( "load", () => {
  // The code output
  const dataEl = document.querySelector( ".data pre" ).innerHTML;
  // The parent rankings element
  const tableEl = document.querySelector( ".league-table" );
  // The table headers
  const tableHeaderEl = document.querySelector( "#league-standings .header" );
  // Parse JSON for the code output
  const dataJSON = JSON.parse( dataEl );
  // Print a little note in the console
  console.log( "Data from the front end", dataJSON );
  
  // All the teams 
  let teams = dataJSON.data.response[ 0 ].league.standings[ 0 ];
  // The league logo
  let leagueLogoURL = dataJSON.data.response[ 0 ].league.logo;
  // Apply the league logo as a background image inline style
  tableHeaderEl.style.backgroundImage = `url( ${ leagueLogoURL } )`;
  
  // Loop through the teams
  teams.forEach( ( team, index ) => {
    // Make a div for each team
    const teamDiv = document.createElement( "div" );
    // Set up the columns for match results
    const { played, win, draw, lose, goals } = team.all;

    // Add a class to the parent rankings element
    teamDiv.classList.add( "team" );
    // Insert the following markup and data in the parent element
    teamDiv.innerHTML = `
      
${ index + 1 }
${ team.team.name }
${ played }
${ win }
${ draw }
${ lose }
${ goals.for }
${ goals.against }
${ team.points }
`; // Stringify the last five match results for a team const form = team.form.split( "" ); // Loop through the match results form.forEach( ( result ) => { // Make a div for each result const resultEl = document.createElement( "div" ); // Add a class to the div resultEl.classList.add( "result" ); // Evaluate the results resultEl.innerText = result; // If the result a win if ( result === "W" ) { resultEl.classList.add( "win" ); // If the result is a draw } else if ( result === "D" ) { resultEl.classList.add( "draw" ); // If the result is a loss } else { resultEl.classList.add( "lost" ); } // Append the results to the column teamDiv.querySelector( ".form-history" ).append( resultEl ); }); tableEl.append( teamDiv ); }); });

스타일링에 관한 한, 당신은 당신이 원하는 모든 것을 자유롭게 할 수 있습니다! 작업하고 싶은 것이 있으면 시작점으로 사용할 수 있는 전체 스타일 세트가 있습니다.

나는 SCSS에서 스타일을 지정했습니다. @wordpress/create-block 패키지는 즉시 지원합니다. 운영 npm run start 명령줄에서 SCSS 파일을 보고 저장할 때 CSS로 컴파일합니다. 또는 다음을 사용할 수 있습니다. npm run build SCSS를 컴파일하고 플러그인 번들의 나머지 부분을 빌드하기 위해 저장할 때마다

SCSS 보기
body {
  background: linear-gradient(to right, #8f94fb, #4e54c8);
}

.data pre {
  display: none;
}

.header {
  display: grid;
  gap: 1em;
  padding: 10px;
  grid-template-columns: 1fr 1fr 3fr 4fr 3fr;
  align-items: center;
  color: white;
  font-size: 16px;
  font-weight: 600;
  background-repeat: no-repeat;
  background-size: contain;
  background-position: right;
}

.frontend#league-standings {
  width: 900px;
  margin: 60px 0;
  max-width: unset;
  font-size: 16px;

  .header {
    .stats {
      display: flex;
      gap: 15px;

      & > div {
        width: 30px;
      }
    }
  }
}

.league-table {
  background: white;
  box-shadow:
    rgba(50, 50, 93, 0.25) 0px 2px 5px -1px,
    rgba(0, 0, 0, 0.3) 0px 1px 3px -1px;
  padding: 1em;

  .position {
    width: 20px;
  }

  .team {
    display: grid;
    gap: 1em;
    padding: 10px 0;
    grid-template-columns: 1fr 1fr 3fr 4fr 3fr;
    align-items: center;
  }

  .team:not(:last-child) {
    border-bottom: 1px solid lightgray;
  }

  .team-logo img {
    width: 30px;
  }

  .stats {
    display: flex;
    gap: 15px;
  }

  .stats > div {
    width: 30px;
    text-align: center;
  }

  .form-history {
    display: flex;
    gap: 5px;
  }

  .form-history > div {
    width: 25px;
    height: 25px;
    text-align: center;
    border-radius: 3px;
    font-size: 15px;
  }

  .form-history .win {
    background: #347d39;
    color: white;
  }

  .form-history .draw {
    background: gray;
    color: white;
  }

  .form-history .lost {
    background: lightcoral;
    color: white;
  }
}

여기 데모가 있습니다!

확인해 보세요. 방금 데이터를 가져와 WordPress 사이트의 프런트 엔드에서 렌더링하는 블록 플러그인을 만들었습니다.

API를 찾았습니다. fetch()-ed 데이터를 WordPress 데이터베이스에 저장하고 구문 분석하고 일부 HTML 마크업에 적용하여 프런트 엔드에 표시합니다. 단일 튜토리얼로 나쁘지 않죠?

다시 말하지만, 순위가 테마의 프런트 엔드 외에도 블록 편집기에서 렌더링되도록 동일한 종류의 작업을 수행할 수 있습니다. 그러나 프런트 엔드에 초점을 맞추면 WordPress 블록에서 데이터 가져오기가 작동하는 방식과 표시를 위해 데이터를 구조화하고 렌더링하는 방법을 알 수 있습니다.

타임 스탬프 :

더보기 CSS 트릭