• Resolved WebTrooper

    (@webtrooper)


    Hello, I’m having trouble using a variable in my graphql query. I think it’s clear what I’m trying to do here. This is in single.php

    <?php
    
    $post_slug=get_post_field( 'post_name', get_post() );
    
    $graphql = graphql([
    'query' => ' {
    post(idType: SLUG, id: $post_slug) {
    title
    content
    date
    }
    }'
    ]);
    
    echo '<pre>';
    var_dump($graphql);
    echo '</pre>';
    ?>
    

    The result says $post_slug is undefined.

    array(2) {
      ["errors"]=>
      array(1) {
        [0]=>
        array(3) {
          ["message"]=>
          string(37) "Variable "$post_slug" is not defined."
          ["extensions"]=>
          array(1) {
            ["category"]=>
            string(7) "graphql"
          }
          ["locations"]=>
          array(2) {
            [0]=>
            array(2) {
              ["line"]=>
              int(2)
              ["column"]=>
              int(24)
            }
            [1]=>
            array(2) {
              ["line"]=>
              int(1)
              ["column"]=>
              int(2)
            }
          }
        }
      }
      ["extensions"]=>
      array(1) {
        ["debug"]=>
        array(0) {
        }
      }
    }
Viewing 1 replies (of 1 total)
  • Hi,

    To pass the variables to query strings, graphql() expects a named query ( name is optional ).

    Following is the updated snippet,

    
    <?php
    $post_slug = get_post_field( 'post_name', get_post() );
    
    $graphql = graphql([
      'query' => '
        query GetPost( $post_slug: ID! ) {
          post(idType: SLUG, id: $post_slug) {
            title
            content
            date
          }
      }',
      'variables' => [
        'post_slug' => 'test-previews',
      ],
    ]);

    For more details you can refer:
    graphql() ref
    Using variables in graphql queries

    Hope this helps,

    Thank you,

Viewing 1 replies (of 1 total)
  • The topic ‘How to use PHP variable in a query’ is closed to new replies.