쿼리 라이브러리
쿼리 라이브러리CSV에서 Bricks 게시물을 일괄 생성하기

CSV에서 Bricks 게시물을 일괄 생성하기

이 쿼리는 CSV 파일에서 데이터를 가져와 여러 Bricks 게시물을 일괄 생성합니다.

이 쿼리를 사용하려면 Bricks 확장 기능이 활성화되어 있어야 합니다.

게시물을 생성하려면 다음을 제공해야 합니다.

  • 콘텐츠와 Bricks 데이터에 변수를 포함한 복제 원본 Bricks 템플릿
  • 새 게시물을 생성할 Bricks 지원 커스텀 게시물 타입
  • 동적 콘텐츠가 담긴 CSV 파일의 URL

CSV 파일의 열 이름에는 변수 이름을 사용하며, 각 열의 값이 해당 변수의 값이 됩니다. 쿼리는 CSV 파일의 각 행을 처리하여 개별 Bricks 게시물을 생성합니다.

예를 들어, 다음 CSV 파일로 3개의 게시물이 생성됩니다.

pageTitle,heroTitle,heroDesc,heroButtonText1,heroButtonLink1,heroButtonText2,heroButtonLink2
"Welcome to Our Site","<h2>Welcome</h2>","<p>This is the main content.</p>","A brief description","https://mysite.com/pricing","Another description","https://mysite.com/more"
"About Us","<h2>About</h2>","<p>Learn more about our company.</p>","Company information","https://mysite.com/about","We are humans","https://mysite.com/humans"
"Contact","<h2>Contact</h2>","<p>Get in touch with us.</p>","Contact details","https://mysite.com/contact","Subscribe to our newsletter","https://mysite.com/newsletter"

페이지 콘텐츠와 Bricks 데이터에는 {...}로 둘러싸인 변수가 포함됩니다.

위의 CSV에 대응하여, 원본 Bricks 게시물에서는 다음 변수를 사용할 수 있습니다.

  • {pageTitle}
  • {heroTitle}
  • {heroDesc}
  • {heroButtonText1}
  • {heroButtonLink1}
  • {heroButtonText2}
  • {heroButtonLink2}

예를 들어, 페이지 제목에는 "{pageTitle}" 또는 "Welcome to {pageTitle}" 등을 설정할 수 있습니다.

마찬가지로, Bricks의 heading 요소는 text 속성에 "{heroTitle}" 또는 "Welcome to {heroTitle}" 등을 설정할 수 있습니다.

그리고 button 요소는 Link => URL 속성에 "{heroButtonLink1}" 또는 "{heroButtonLink2}"를 설정합니다.

이 쿼리에는 다음 변수가 필요합니다.

  • $url: CSV 파일의 URL(헤더 행 포함)
  • $templateId: 새 게시물 생성에 사용할 Bricks 템플릿(CPT bricks_template
  • $customPostType: 새 게시물을 생성할 Bricks 지원 커스텀 게시물 타입
  • $status: 생성된 게시물의 상태(기본값: "draft"
query InitializeDynamicVariables(
  $customPostType: CustomPostEnumString!
)
  @configureWarningsOnExportingDuplicateVariable(enabled: false)
{
  emptyBool: _echo(value: false)
    @export(as: "bricksIsEnabledForCustomPostType")
    @export(as: "hasTemplate")
    @remove
 
  emptyList: _echo(value: [])
    @export(as: "adaptedBricksDataTextElementTextsList")
    @export(as: "adaptedBricksDataLinkElementLinksList")
    @export(as: "newCustomPostIds")
    @export(as: "customPostInputs")
    @remove
 
  useWhichPageBuilderWithCustomPostType(customPostType: $customPostType)
  bricksIsEnabledForCustomPostType: _equals(
    value1: $__useWhichPageBuilderWithCustomPostType
    value2: "bricks"
  )
    @export(as: "bricksIsEnabledForCustomPostType")
}
 
query GetBricksCustomPostAndExportData($templateId: ID!)
  @depends(on: "InitializeDynamicVariables")
  @include(if: $bricksIsEnabledForCustomPostType)
{
  bricksTemplate: customPost(by: { id: $templateId }, customPostTypes: "bricks_template", status: any) {
    # Fields to be duplicated
    author @export(as: "authorID") {
      id
    }
    rawContent @export(as: "rawContent")
    rawExcerpt @export(as: "excerpt")
    featuredImage @export(as: "featuredImageID") {
      id
    }
    rawTitle @export(as: "title")
 
    metaKeys(filter: { exclude: [
      "_thumbnail_id",
      "_edit_last",
      "_edit_lock",
      "_pingme",
      "_encloseme",
      "_trackbackme",
      "enclosure",
      "_wp_trash_meta_status",
      "_wp_trash_meta_time",
      "_wp_desired_post_slug",
      "_wp_old_slug",
      "_wp_old_date",
    ] })
    meta(keys: $__metaKeys) 
      @export(as: "meta")
 
    bricksDataTextElements: bricksData(filterBy: {include: [
      "heading",
      "text",
      "text-basic",
      "button",
      "dropdown",
    ]})
      @underEachArrayItem(
        affectDirectivesUnderPos: [1, 3]
      )
        @underJSONObjectProperty(by: { key: "id" })
          @export(as: "bricksDataTextElementIDs")
        @underJSONObjectProperty(
          by: { path: "settings.text" }
          failIfNonExistingKeyOrPath: false
        )
          @export(as: "bricksDataTextElementTexts")
 
    bricksDataLinkElements: bricksData(filterBy: {include: [
      "text-link",
      "button",
    ]})
      @underEachArrayItem(
        affectDirectivesUnderPos: [1, 3]
      )
        @underJSONObjectProperty(by: { key: "id" })
          @export(as: "bricksDataLinkElementIDs")
        @underJSONObjectProperty(
          by: { path: "settings.link.url" }
          failIfNonExistingKeyOrPath: false
        )
          @export(as: "bricksDataLinkElementLinks")
  }
 
  hasTemplate: _notNull(value: $__bricksTemplate)
    @export(as: "hasTemplate")
}
 
query GetAndFormatDataFromCSV(
  $url: URL!
)
  @depends(on: "GetBricksCustomPostAndExportData")
  @include(if: $bricksIsEnabledForCustomPostType)
  @include(if: $hasTemplate)
{
  _sendHTTPRequest(input: {
    url: $url,
    method: GET
  }) {
    body
    csv: _strParseCSV(
      string: $__body
    )
      @export(as: "csvPostEntries")
      @underArrayItem(
        index: 0
        passOnwardsAs: "csvPostEntry"
        affectDirectivesUnderPos: [1, 2]
      )
        @applyField(
          name: "_objectProperties",
          arguments: {
            object: $csvPostEntry,
          },
          passOnwardsAs: "csvKeys"
        )
        @exportFrom(
          scopedDynamicVariable: $csvKeys,
          as: "csvKeys"
        )      
  }
}
 
query GenerateVariablePlaceholderNames
  @depends(on: "GetAndFormatDataFromCSV")
  @include(if: $bricksIsEnabledForCustomPostType)
  @include(if: $hasTemplate)
{
    csvKeyPlaceholderNames: _echo(value: $csvKeys)
      @underEachArrayItem(passValueOnwardsAs: "entryKey")
        @applyField(
          name: "_sprintf",
          arguments: {
            string: "{%s}",
            values: [$entryKey],
          },
          setResultInResponse: true
        )
      @export(as: "csvKeyPlaceholderNames")
}
 
query GenerateCustomPostInputs(
  $customPostType: CustomPostEnumString!
  $status: CustomPostStatusEnum! = draft
)
  @depends(on: "GenerateVariablePlaceholderNames")
  @include(if: $bricksIsEnabledForCustomPostType)
  @include(if: $hasTemplate)
{
  customPostInputs: _echo(value: $csvPostEntries)
    @underEachArrayItem(
      passValueOnwardsAs: "csvPostEntry"
      affectDirectivesUnderPos: [1, 2, 3, 4, 5, 6, 7, 8]
    )
      @applyField(
        name: "_objectValues",
        arguments: {
          object: $csvPostEntry,
        },
        passOnwardsAs: "replaceTo"
      )
      @applyField(
        name: "_strReplaceMultiple",
        arguments: {
          search: $csvKeyPlaceholderNames,
          replaceWith: $replaceTo,
          in: $title
        },
        passOnwardsAs: "adaptedTitle"
      )
      @applyField(
        name: "_strReplaceMultiple",
        arguments: {
          search: $csvKeyPlaceholderNames,
          replaceWith: $replaceTo,
          in: $excerpt
        },
        passOnwardsAs: "adaptedExcerpt"
      )
      # Already create (and export) the inputs for the mutation
      @applyField(
        name: "_echo",
        arguments: {
          value: {
            status: $status,
            customPostType: $customPostType,
            authorBy: {
              id: $authorID
            },
            title: $adaptedTitle,
            excerpt: $adaptedExcerpt
            contentAs: {
              html: $rawContent
            },
            featuredImageBy: {
              id: $featuredImageID
            },
            meta: $meta
          }
        },
        setResultInResponse: true
      )
      # Already export the inputs to update the Bricks data
      @applyField(
        name: "_strArrayReplaceMultiple",
        arguments: {
          search: $csvKeyPlaceholderNames,
          replaceWith: $replaceTo,
          in: $bricksDataTextElementTexts
        },
        passOnwardsAs: "adaptedBricksDataTextElementTextsList"
      )
      @exportFrom(
        scopedDynamicVariable: $adaptedBricksDataTextElementTextsList,
        as: "adaptedBricksDataTextElementTextsList"
      )
      @applyField(
        name: "_strArrayReplaceMultiple",
        arguments: {
          search: $csvKeyPlaceholderNames,
          replaceWith: $replaceTo,
          in: $bricksDataLinkElementLinks
        },
        passOnwardsAs: "adaptedBricksDataLinkElementLinksList"
      )
      @exportFrom(
        scopedDynamicVariable: $adaptedBricksDataLinkElementLinksList,
        as: "adaptedBricksDataLinkElementLinksList"
      )
    @export(as: "customPostInputs")
}
 
query AdaptBricksDataElementsFormat
  @depends(on: "GenerateCustomPostInputs")
  @include(if: $bricksIsEnabledForCustomPostType)
  @include(if: $hasTemplate)
{
  adaptedBricksDataTextElementsList: _echo(value: $adaptedBricksDataTextElementTextsList)
    @underEachArrayItem
      @underEachArrayItem(
        passIndexOnwardsAs: "index"
        passValueOnwardsAs: "bricksDataTextElementText"
        affectDirectivesUnderPos: [1, 2]
      )
        @applyField(
          name: "_arrayItem"
          arguments: {
            array: $bricksDataTextElementIDs,
            position: $index
          }
          passOnwardsAs: "bricksElementID"
        )
        @applyField(
          name: "_echo"
          arguments: {
            value: {
              id: $bricksElementID,
              settings: {
                text: $bricksDataTextElementText
              }
            }
          },
          setResultInResponse: true
        )
      @export(as: "adaptedBricksDataTextElementsList")
 
  adaptedBricksDataLinkElementsList: _echo(value: $adaptedBricksDataLinkElementLinksList)
    @underEachArrayItem
      @underEachArrayItem(
        passIndexOnwardsAs: "index"
        passValueOnwardsAs: "bricksDataLinkElementLink"
        affectDirectivesUnderPos: [1, 2]
      )
        @applyField(
          name: "_arrayItem"
          arguments: {
            array: $bricksDataLinkElementIDs,
            position: $index
          }
          passOnwardsAs: "bricksElementID"
        )
        @applyField(
          name: "_echo"
          arguments: {
            value: {
              id: $bricksElementID,
              settings: {
                link: {
                  url: $bricksDataLinkElementLink
                }
              }
            }
          },
          setResultInResponse: true
        )
      @export(as: "adaptedBricksDataLinkElementsList")
}
 
mutation CreatePostsFromCSVEntries
  @depends(on: "AdaptBricksDataElementsFormat")
  @include(if: $bricksIsEnabledForCustomPostType)
  @include(if: $hasTemplate)
{
  createCustomPosts(inputs: $customPostInputs) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    customPost {
      # Fields not to be duplicated
      id
        @export(
          as: "newCustomPostIds",
          type: LIST,
        )
      slug
      date
      status
 
      # Fields to be duplicated
      customPostType
      author {
        id
      }
      rawContent
      excerpt
      featuredImage {
        id
      }
      title
      
      metaKeys
      meta(keys: $__metaKeys)
      bricksData
    }
  }
}
 
query CreateUpdateBricksDataInputs
  @depends(on: "CreatePostsFromCSVEntries")
  @include(if: $bricksIsEnabledForCustomPostType)
  @include(if: $hasTemplate)
{
  bricksMergeCustomPostTextElementDataItemInputs: _echo(value: $newCustomPostIds)
    @underEachArrayItem(
      passIndexOnwardsAs: "index"
      passValueOnwardsAs: "newCustomPostId"
      affectDirectivesUnderPos: [1, 2]
    )
      @applyField(
        name: "_arrayItem"
        arguments: {
          array: $adaptedBricksDataTextElementsList,
          position: $index
        }
        passOnwardsAs: "adaptedBricksDataTextElements"
      )
      @applyField(
        name: "_echo",
        arguments: {
          value: {
            customPostID: $newCustomPostId
            elements: $adaptedBricksDataTextElements
          }
        },
        setResultInResponse: true
      )
    @export(as: "bricksMergeCustomPostTextElementDataItemInputs")
 
  bricksMergeCustomPostLinkElementDataItemInputs: _echo(value: $newCustomPostIds)
    @underEachArrayItem(
      passIndexOnwardsAs: "index"
      passValueOnwardsAs: "newCustomPostId"
      affectDirectivesUnderPos: [1, 2]
    )
      @applyField(
        name: "_arrayItem"
        arguments: {
          array: $adaptedBricksDataLinkElementsList,
          position: $index
        }
        passOnwardsAs: "adaptedBricksDataLinkElements"
      )
      @applyField(
        name: "_echo",
        arguments: {
          value: {
            customPostID: $newCustomPostId
            elements: $adaptedBricksDataLinkElements
          }
        },
        setResultInResponse: true
      )
    @export(as: "bricksMergeCustomPostLinkElementDataItemInputs")
 
  bricksRegenerateCustomPostElementIDSetInputs: _echo(value: $newCustomPostIds)
    @underEachArrayItem(passValueOnwardsAs: "newCustomPostId")
      @applyField(
        name: "_echo",
        arguments: {
          value: {
            customPostID: $newCustomPostId
          }
        },
        setResultInResponse: true
      )
    @export(as: "bricksRegenerateCustomPostElementIDSetInputs")
}
 
query AdaptBricksDataInputs
  @depends(on: "CreateUpdateBricksDataInputs")
  @include(if: $bricksIsEnabledForCustomPostType)
  @include(if: $hasTemplate)
{
  bricksMergeCustomPostElementDataItemInputs: _arrayMerge(arrays: [
    $bricksMergeCustomPostTextElementDataItemInputs,
    $bricksMergeCustomPostLinkElementDataItemInputs
  ])
    @export(as: "bricksMergeCustomPostElementDataItemInputs")
}
 
mutation UpdateAndRegenerateBricksData
  @depends(on: "AdaptBricksDataInputs")
  @include(if: $bricksIsEnabledForCustomPostType)
  @include(if: $hasTemplate)
{
  bricksMergeCustomPostElementDataItems(inputs: $bricksMergeCustomPostElementDataItemInputs) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    customPost {
      __typename
      ...on CustomPost {
        id
        bricksData
      }
    }
  }
 
  bricksRegenerateCustomPostElementIDSets(inputs: $bricksRegenerateCustomPostElementIDSetInputs) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    customPost {
      __typename
      ...on CustomPost {
        id
        bricksData
      }
    }
  }
}