Bibliothèque de queries
Bibliothèque de queriesInsérer un bloc dans tous les articles

Insérer un bloc dans tous les articles

Cette requête identifie le n-ième bloc d'un type donné ("wp:paragraph" par défaut) dans tous les articles, et place le contenu HTML du bloc personnalisé fourni juste après.

La variable $injectBlockMarkup doit recevoir le balisage HTML complet du bloc (avec les guillemets échappés pour l'entrée JSON). Par exemple :

<!-- mycompany:black-friday-campaign-video --><figure class=\"wp-block-video\"><video controls src=\"https://mysite.com/videos/BlackFriday2023.mp4\"></video></figure><!-- /mycompany:black-friday-campaign-video -->

Cette requête nécessite que le point de terminaison ait les Mutations imbriquées activées.

query CreateRegex(
  $searchBlockType: String! = "wp:paragraph"
  $injectAfterBlockCount: Int = 1
  $injectBlockMarkup: String!
) {
  endingBlockMarkup: _sprintf(
    string: "<!-- /%s -->",
    values: [$searchBlockType]
  )
    @remove
  endingBlockMarkupArray: _arrayPad(
    array: [],
    length: $injectAfterBlockCount,
    value: $__endingBlockMarkup
  )
    @remove
  regexString: _arrayJoin(
    array: $__endingBlockMarkupArray,
    separator: "[\\s\\S]+"
  )
    @remove
  regex: _sprintf(
    string: "#(%s)#U",
    values: [$__regexString]
  )
    @export(as: "regex")
    @remove
  replaceWith: _sprintf(
    string: "$1%s",
    values: [$injectBlockMarkup]
  )
    @export(as: "replaceWith")
    @remove
}
 
mutation InsertBlockInAllPosts
  @depends(on: "CreateRegex")
{
  posts: posts(
    pagination: { limit: -1 }
  ) {
    id
    rawContent
    adaptedRawContent: _strRegexReplace(
      in: $__rawContent,
      searchRegex: $regex,
      replaceWith: $replaceWith,
      limit: 1
    )
    update(input: {
      contentAs: { html: $__adaptedRawContent },
    }) {
      status
      errors {
        __typename
        ...on ErrorPayload {
          message
        }
      }
      post {
        id
        rawContent
      }
    }
  }
}