Thư viện Queries
Thư viện QueriesNhập HTML từ các URL thành bài viết mới trong WordPress

Nhập HTML từ các URL thành bài viết mới trong WordPress

Query này nhập các trang HTML từ các URL đã cho thành các bài viết mới trong WordPress.

Từ mỗi URL, nó lấy tiêu đề từ <title>...</title> trong phần meta, và nội dung từ <body>...</body>, hoặc có thể tùy chỉnh để lấy từ một phần tử HTML bên trong cụ thể bằng cách sử dụng biến $contentMatchInnerRegex.

Với $contentMatchInnerRegex, chúng ta có thể chỉ định phần cụ thể nào trong HTML của <body> cần được trích xuất.

Ví dụ, nếu nội dung cần được trích xuất từ:

<article class="main">...</article>

...chúng ta có thể trích xuất nó bằng:

{
  "contentMatchInnerRegex": ".*?<\\s*?article\\b[^>]*>(.*?)<\\/article\\b[^>]*>.*?"
}
query GenerateURLInputs(
  $urls: [URL!]!
  $contentMatchInnerRegex: String! = "(.*?)"
) {
  urlInputs: _echo(value: $urls)
    @underEachArrayItem(
      passValueOnwardsAs: "url"
    )
      @applyField(
        name: "_echo",
        arguments: {
          value: {
            url: $url,
            method: GET
          }
        },
        setResultInResponse: true
      )
    @export(as: "urlInputs")
    @remove
  contentMatchRegex: _sprintf(
    string: "/(?:<!DOCTYPE html>)?<\\s*?html\\b[^>]*>.*?<\\s*?body\\b[^>]*>%s<\\/body\\b[^>]*>.*?<\\/html\\b[^>]*>/sim",
    values: [$contentMatchInnerRegex]
  )
    @export(as: "contentMatchRegex")
}
 
query RequestPages
  @depends(on: "GenerateURLInputs")
{
  urlContents: _sendHTTPRequests(inputs: $urlInputs, async: false) {
    statusCode
    body
      @remove
    title: _strRegexReplace(
      searchRegex: "/(?:<!DOCTYPE html>)?<\\s*?html\\b[^>]*>.*?<head\\b[^>]*>.*?<\\s*?title\\b[^>]*>(.*?)<\\/title\\b[^>]*>.*?<\\/head\\b[^>]*>(.*?)<\\/html\\b[^>]*>/sim"
      replaceWith: "$1"
      in: $__body
    )
    content: _strRegexReplace(
      searchRegex: $contentMatchRegex
      replaceWith: "$1"
      in: $__body
    )
    createPostInput: _echo(value: {
      status: publish,
      title: $__title
      contentAs: {
        html: $__content
      }
    })
      @export(as: "createPostInputs", type: LIST)
  }
}
 
mutation CreatePostsFromURLs
  @depends(on: "RequestPages")
{
  createPosts(inputs: $createPostInputs) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    post {
      id
      status
      title
      content
    }
  }
}