스키마 튜토리얼
스키마 튜토리얼레슨 17: 필수 블록 자동 추가

레슨 17: 필수 블록 자동 추가

새 게시물이 생성될 때마다 자동화 기능을 사용하여 게시물의 콘텐츠를 검증하고 수정할 수 있습니다.

이 튜토리얼 레슨의 쿼리는 특정 필수 블록이 게시물에 존재하는지 확인하고, 없는 경우 해당 블록을 추가합니다.

누락된 블록을 추가하는 GraphQL 쿼리

이 GraphQL 쿼리가 작동하려면, 엔드포인트에 적용된 스키마 설정에서 중첩 뮤테이션이 활성화되어 있어야 합니다.

이 GraphQL 쿼리는 필수 블록 wp:comments가 이미 게시물에 추가되어 있는지 확인합니다. 없는 경우, 콘텐츠 하단에 추가됩니다.

이 콘텐츠를 슬러그 insert-mandatory-comments-block-if-missing으로 Persisted Query로 저장하세요.

query CheckIfCommentsBlockExists($postId: ID!) {
  posts(
    filter: {
      ids: [$postId]
      search: "\"<!-- /wp:comments -->\""
    }
  ) {
    id
  }
  blockExists: _notEmpty(value: $__posts)
    @export(as: "blockExists")
}
 
mutation MaybeInsertCommentsBlock($postId: ID!)
  @depends(on: "CheckIfCommentsBlockExists")
  @skip(if: $blockExists)
{
  post(by: { id: $postId }) {
    id
    rawContent
    adaptedRawContent: _strAppend(
      after: $__rawContent
      append: """
 
<!-- wp:comments -->
<div class="wp-block-comments"><!-- wp:comments-title /-->
 
<!-- wp:comment-template -->
<!-- wp:columns -->
<div class="wp-block-columns"><!-- wp:column {"width":"40px"} -->
<div class="wp-block-column" style="flex-basis:40px"><!-- wp:avatar {"size":40,"style":{"border":{"radius":"20px"}}} /--></div>
<!-- /wp:column -->
 
<!-- wp:column -->
<div class="wp-block-column"><!-- wp:comment-author-name {"fontSize":"small"} /-->
 
<!-- wp:group {"style":{"spacing":{"margin":{"top":"0px","bottom":"0px"}}},"layout":{"type":"flex"}} -->
<div class="wp-block-group" style="margin-top:0px;margin-bottom:0px"><!-- wp:comment-date {"fontSize":"small"} /-->
 
<!-- wp:comment-edit-link {"fontSize":"small"} /--></div>
<!-- /wp:group -->
 
<!-- wp:comment-content /-->
 
<!-- wp:comment-reply-link {"fontSize":"small"} /--></div>
<!-- /wp:column --></div>
<!-- /wp:columns -->
<!-- /wp:comment-template -->
 
<!-- wp:comments-pagination -->
<!-- wp:comments-pagination-previous /-->
 
<!-- wp:comments-pagination-numbers /-->
 
<!-- wp:comments-pagination-next /-->
<!-- /wp:comments-pagination -->
 
<!-- wp:post-comments-form /--></div>
<!-- /wp:comments -->   
 
      """
    )
    update(input: {
      contentAs: { html: $__adaptedRawContent },
    }) {
      status
      errors {
        __typename
        ...on ErrorPayload {
          message
        }
      }
      post {
        id
        rawContent
      }
    }
  }
}

Persisted Query를 실행하는 훅 추가

Internal GraphQL Server 는 기본적으로 자체 설정에서 정의된 스키마 설정을 적용합니다.

따라서 이 GraphQL 쿼리가 작동하려면, Internal GraphQL Server 에 적용된 스키마 설정에서 중첩 뮤테이션이 활성화되어 있어야 합니다.

이 PHP 코드는 WordPress 액션 draft_post 에 훅을 걸어 (Internal GraphQL Server 확장 기능을 통해) Persisted Query를 실행합니다.

use GatoGraphQL\InternalGraphQLServer\GraphQLServer;
use WP_Post;
 
add_action(
  'draft_post',
  function (int $postID): void {
    GraphQLServer::executePersistedQuery(
      'insert-mandatory-comments-block-if-missing',
      [
        'postId' => $postID,
      ],
      'MaybeInsertCommentsBlock'
    );
  }
);