This is using WPGraphql with WordPress but I believe it's a general PHP and/or Graphql issue. I've been searching for 2 days now, and everything I've found is specific to some library or framework or otherwise not helpful. Any help with this is super appreciated.
The code below creates a variable $post_slug which contains the slug of the current post.
If I replace id: $post_slug with an actual post slug (id: "my-groovy-post") it works, but apparently $post_slug is undefined within the query.
<?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 results of my query
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(27)
}
[1]=>
array(2) {
["line"]=>
int(1)
["column"]=>
int(2)
}
}
}
}
["extensions"]=>
array(1) {
["debug"]=>
array(1) {
[0]=>
array(2) {
["type"]=>
string(19) "DEBUG_LOGS_INACTIVE"
["message"]=>
string(86) "GraphQL Debug logging is not active. To see debug logs, GRAPHQL_DEBUG must be enabled."
}
}
}
}
pinstead. So I don't really know graphQL but I can use google, and it seems it wants you to quote the field so it can be treated as a string in the context of the graphQL query. So you can add escaped quote marks, like this: 3v4l.org/XY9SG . Or you go back to single-quoted PHP string, add the quote marks verbatim and concatenate the slug value, like this: 3v4l.org/suI5r . Same result either way