graphql

Given an array with a Query and optional Variables and Operation Name this executes a GraphQL request.

graphql( $operation );

Paramaters

  • $operation (array): An associative array of key/value pairs for the operation to execute.
    • $query (string): The Query string to execute. This can be a mutation as well.
    • $variables (array): Array of variables to be used with the operation
    • $operation_name (string): The name of the operation.

Source

File: access-functions.php

Examples

The graphql() function can be used to execute GraphQL operations within PHP. WPGraphQL uses this method heavily within it’s automated test suites.

Query a List of Posts in PHP

Here’s an example of querying a list of posts using the graphql() function:

$graphql = graphql([
  'query' => '
  {
    posts {
      nodes {
        id
        title
      }
    }
  }
  '
]);

Query with Arguments in PHP

Here’s an example of querying with arguments in PHP.

$graphql = graphql([
  'query' => '
  query GetPosts( $first: Int ) {
    posts {
      nodes {
        id
        title
      }
    }
  }
  ',
  'variables' => [
    'first' => 5, // <-- This value could be dynamic from a shortcode/gutenberg block, a form submission, etc.
  ],
]);