บทช่วยสอน Schema
บทช่วยสอน Schemaบทเรียนที่ 8: การย้ายเว็บไซต์

บทเรียนที่ 8: การย้ายเว็บไซต์

เราสามารถรัน GraphQL queries แบบกลุ่มเพื่อปรับเนื้อหาในเว็บไซต์เมื่อย้ายไปยังโดเมนใหม่ ย้ายหน้าไปยัง URL อื่น หรืออื่น ๆ ได้

เพื่อให้ GraphQL query นี้ทำงานได้ Schema Configuration ที่นำไปใช้กับ endpoint จำเป็นต้องเปิดใช้งาน Nested Mutations

การปรับเนื้อหาให้เข้ากับโดเมนใหม่

GraphQL query นี้จะกรองโพสต์ทั้งหมดที่มี "https://my-old-domain.com" อยู่ในเนื้อหาก่อน แล้วแทนที่สตริงนี้ด้วย "https://my-new-domain.com":

mutation ReplaceOldWithNewDomainInPosts {
  posts(
    filter: {
      search: "https://my-old-domain.com"
    }
  ) {
    id
    rawContent
    adaptedRawContent: _strReplace(
      search: "https://my-old-domain.com"
      replaceWith: "https://my-new-domain.com"
      in: $__rawContent
    )
    update(input: {
      contentAs: { html: $__adaptedRawContent }
    }) {
      status
      errors {
        __typename
        ...on ErrorPayload {
          message
        }
      }
      post {
        id
        rawContent
      }
    }
  }
}

การปรับเนื้อหาให้เข้ากับ URL ของโพสต์หรือหน้าใหม่

หลังจากเปลี่ยน slug ของโพสต์หรือหน้าแล้ว เราสามารถแปลงเนื้อหาทั้งหมดให้ชี้ไปยัง URL ใหม่ได้

GraphQL นี้จะดึงโดเมนจากการตั้งค่า WordPress "siteurl" ก่อน เพื่อสร้าง URL เก่าและใหม่ของหน้าขึ้นมาใหม่:

query ExportData(
  $oldPageSlug: String!
  $newPageSlug: String!
) {
  siteURL: optionValue(name: "siteurl")
 
  oldPageURL: _strAppend(
    after: $__siteURL,
    append: $oldPageSlug
  ) @export(as: "oldPageURL")
 
  newPageURL: _strAppend(
    after: $__siteURL,
    append: $newPageSlug
  ) @export(as: "newPageURL")
}
 
mutation ReplaceOldWithNewURLInPosts
  @depends(on: "ExportData")
{
  posts(
    filter: {
      search: $oldPageURL
    },
    sort: { by: ID, order: ASC }
  ) {
    id
    rawContent
    adaptedRawContent: _strReplace(
      search: $oldPageURL
      replaceWith: $newPageURL
      in: $__rawContent
    )
    update(input: {
      contentAs: { html: $__adaptedRawContent }
    }) {
      status
      errors {
        __typename
        ...on ErrorPayload {
          message
        }
      }
      post {
        id
        rawContent
      }
    }
  }
}

จากนั้นเราระบุ slug ของหน้าเก่าและใหม่ผ่านดิกชันนารี variables:

{
  "oldPageSlug": "/privacy/",
  "newPageSlug": "/user-privacy/"
}