通过 API 编写代码
通过 API 编写代码向WP-CLI注入多个资源

向WP-CLI注入多个资源

在指南「补充WP-CLI」中,我们仅检索了(并注入到WP-CLI的)单个用户ID。现在,让我们在执行单个GraphQL查询的同时检索多个用户ID。

在此GraphQL查询中:

  • 我们从查询中删除pagination参数,以检索所有具有西班牙语区域设置的用户列表
  • 我们使用 Multiple Query Execution 将用户ID列表导出到动态变量$userIDs
  • 我们使用_arrayJoin打印该数组的元素,用空格连接各项,并存储在别名spanishLocaleUserIDs
  • 我们执行操作FormatAndPrintData
# This query is stored in file "find-multiple-users-with-spanish-locale.gql"
query RetrieveData {
  users(
    filter: {
      metaQuery: {
        key: "locale",
        compareBy: {
          stringValue: {
            value: "es_[A-Z]+"
            operator: REGEXP
          }
        }
      }
    }
  ) {
    id @export(as: "userIDs", type: LIST)
    name
    locale: metaValue(key: "locale")
  }
}
 
query FormatAndPrintData @depends(on: "RetrieveData") {
  spanishLocaleUserIDs: _arrayJoin(
    array: $userIDs,
    separator: " "
  )
}

此查询的响应将为:

{
  "data": {
    "users": [
      {
        "id": 3,
        "name": "Subscriber Bennett",
        "locale": "es_AR"
      },
      {
        "id": 2,
        "name": "Blogger Davenport",
        "locale": "es_ES"
      }
    ],
    "spanishLocaleUserIDs": "3 2"
  }
}

执行查询时,请求体中的字典必须指明要执行的操作名称("FormatAndPrintData"):

GRAPHQL_QUERY=$(cat find-multiple-users-with-spanish-locale.gql)
GRAPHQL_BODY="{\"operationName\": \"FormatAndPrintData\", \"query\": \"$(echo $GRAPHQL_QUERY | tr '\n' ' ' | sed 's/"/\\"/g')\"}"
GRAPHQL_RESPONSE=$(curl \
  -X POST \
  -H "Content-Type: application/json" \
  -d $GRAPHQL_BODY \
  https://mysite.com/graphql/)

我们还必须调整正则表达式(由于新的别名、ID之间的空格以及此字符串周围的引号):

SPANISH_LOCALE_USER_IDS=$(echo $GRAPHQL_RESPONSE \
  | grep -E -o '"spanishLocaleUserIDs\":"((\d|\s)+)"' \
  | cut -d':' -f2- | cut -d'"' -f2- | rev | cut -d'"' -f2- | rev)

打印变量SPANISH_LOCALE_USER_IDS的内容,我们将获得所有ID,以空格分隔:

echo $SPANISH_LOCALE_USER_IDS
# Response:
# 3 2

现在我们可以将所有ID一并注入到WP-CLI命令中(如果该命令支持),或者逐一迭代并分别执行命令:

for USER_ID in $(echo $SPANISH_LOCALE_USER_IDS); do wp user update "$(echo $USER_ID)" --locale=fr_FR; done