A GraphQL endpoint for WordPress that's easy to customize.
This is a WordPress Plugin that exposes a GraphQL endpoint at /graphql.
Uses this excellent graphql-php library.
Supports Relay Connections.
composer require mohiohio/graphql-wp
If your aren't familiar with using composer with WordPress I'd recommend using a setup like bedrock. Otherwise you will at the least need to require autoload.php for this to work.
The best way to explore / develop with this is by visiting /graphiql
after installation. This will show you the endpoints and arguments that are available. Note this will only work if you are a logged in admin user.
This is designed to follow WordPress' existing WP Query functions. So as a rule you can pass the same parameters as your can to WP Query*.
*In reality there are a lot of params you can pass to WP_Query, and I've only implemented the ones that I've needed so far. But adding more is trivial as the arguments are just passed directly to the get_posts function, so its just a matter of defining them in the schema.
query example {
wp_query {
posts(first: 10) {
edges {
node {
title
name
terms(taxonomy: "category") {
name
slug
}
}
}
}
}
}
Will give you
{
"data": {
"wp_query": {
"posts": {
"edges": [
{
"node": {
"title": "Dashboard",
"name": "hello-world",
"terms": [
{
"name": "Uncategorized",
"slug": "uncategorized"
}
]
}
}
]
}
}
}
}
And of course you can get an individual post
query example {
wp_post(ID: 9) {
title
content
status
}
}
Any meta fields are available like so
query example {
wp_post(ID: 9) {
title
foo: meta_value(key: "foo")
bar: meta_value(key: "bar")
}
}
If you want to define your own resolver / type you can extend the field schema for a post type like so.
// There is a get_{post_type}_schema call available for each post type
add_filter('graphql-wp/get_post_schema', function($schema) {
$schema['fields'] = function() use ($schema) {
// Note call to "parent" function here
return $schema['fields']() + [
'foo' => [
'type' => Type::string(),
'resolve' => function($post) {
return get_post_meta($post->ID, 'foo' ,true);
}
],
'bar' => [
'type' => Type::string(),
'resolve' => function($post) {
return get_post_meta($post->ID, 'bar' ,true);
}
]
];
};
return $schema;
});
This is how you can add custom post types ( which have custom fields ) to a client specific plugin.
graphql-wp/get_post_types is a good hook for this.
Where $types
is a hash of the schema we are working with, so just add new items into this and you are good to go.
use GraphQL\Type\Definition\Type;
use Mohiohio\GraphQLWP\Type\Definition\Post;
use Mohiohio\GraphQLWP\Type\Definition\Attachment;
class Foo extends Post {
static function getDescription() {
return "A custom post type example, for post type `foo`";
}
static function getFieldSchema() {
return parent::getFieldSchema() + [
'website' => [
'type' => Type::string(),
'resolve' => function($post) {
return get_post_meta($post->ID,'website',true);
},
],
'image' => [
'type' => Attachment::getInstance(),
'resolve' => function($post) {
$attachment_id = get_post_meta($post->ID,'image',true);
return $attachment_id ? get_post($attachment_id) : null;
},
]
];
}
}
add_filter('graphql-wp/schema-types', function($types){
return array_merge($types, [
Foo::getInstance()
]);
});
graphql-wp's People
Forkers
dobbit bouchertommy stevestreza balintsera tony-luisi giastfader graphan sekmet dlackty elvismdev rodrigobacelli jbenesch fastzen rad73 jqueryalmeida hackur deemaxx aaron3 carloscience jasonbahl fahimxyz szepeviktorgraphql-wp's Issues
Endpoint not working on localhost
Hi there,
I am following your tutorial:
- installed wordpress via bedrock
- installed ChromeiQL extension
- configured wordpress to run under http://bedrock.dev on windows machine
But I can not get the endpoint to run
- Full endpoint path: http://bedrock.dev/graphql
- Query:
query PostQuery{ wp_post(ID: 1) { title } }
- output:
SyntaxError: Unexpected token < in JSON at position 0
Does anyone know what (probably simple) configuration I am missing?
Thanks in advance
No endpoint available
Wow i finally did it to successfully install the plugin, but now i don't have any endpoint "/graphql" available.. 😕
My docker-setup runs smoothly on "http://192.168.99.100/web" - showing up with the wordpress landing page on this domain.. so i thought it must be "http://192.168.99.100/web/graphql" now to access it, but i only get 404 back, whatever combo i try...
How can i debug this further down?
graphql error: Unexpected token < in JSON at position 0
I am getting an error despite the activated plugin. The console reports a parse error which points to the usage of a PHP7 null coalescing operator (??):
Parse error</b>: syntax error, unexpected '?' in <b>/wordpress/web/app/plugins/graphql-wp/Type/Definition/WPPost.php
I am running a Docker container on PHP5.6. The graphql-wp repo's composer.json file requires php>=5.6. So, maybe it requires now PHP7. But, I am confused because no one has mentioned this anywhere.
Troubles installing
Hello!
I want to install the plugin.
I have successfully installed composer according to instructions in:
Https://getcomposer.org/download/
My wordpress site is installed on:
/var/www/html/wordpress
And I have redirected the entries to that folder:
<VirtualHost *: 80>
DocumentRoot /var/www /html/wordpress
ServerName mydomain.com
<Directory /var/www/html/wordpress>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow, deny
Allow from all
</Directory>
ErrorLog $ {APACHE_LOG_DIR} /error.log
CustomLog $ {APACHE_LOG_DIR} /access.log combined
</VirtualHost>
I followed the following steps:
cd /var/www/html/wordpress
composer require mohiohio/graphql-wp
And everything seems to be installed correctly:
Using version ^ 0.1.3 for mohiohio / graphql-wp
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 4 installs, 0 updates, 0 removals
- Installing webonyx / graphql-php (v0.6.4): Loading from cache
- Installing mohiohio / wordpress-lib (0.1.4): Loading from cache
- Installing ivome / graphql-relay-php (v0.1.3): Loading from cache
- Installing mohiohio / graphql-wp (0.1.3): Loading from cache
Writing lock file
Generating autoload files
And then I also modified the index.php by adding this line:
require (dirname (__ FILE__). '/vendor/autoload.php');
But when I go to my site:
mydomain.com/graphql
I get a 404 error.
Replace $post with $field
graphql-wp/Type/Definition/ACFImage.php
Line 69 in 8a1a2ee
Coding standard
Please consider following a coding standard.
- PSR-12
- WPCS
- Neutron
- anything!
or my useful frankenstein: https://github.com/szepeviktor/phpcs-psr-12-neutron-hybrid-ruleset#readme
Introduce static analysis :)
composer require --dev "szepeviktor/phpstan-wordpress:^0.6.2" php-stubs/woocommerce-stubs
vendor/bin/phpstan analyze -l 4
phpstan.neon.dist
includes:
- vendor/szepeviktor/phpstan-wordpress/extension.neon
parameters:
level: max
inferPrivatePropertyTypeFromConstructor: true
paths:
- src/
scanFiles:
- vendor/php-stubs/woocommerce-stubs/woocommerce-stubs.php
ignoreErrors:
# Uses func_get_args()
- '#^Function apply_filters(_ref_array)? invoked with [34567] parameters, 2 required\.$#'
Returning children for terms
Hi @timbofield
There is an option to return children for terms
using the following args: parent
or child_of
.
It is fine, but I want to return information about parent and children in the same roundtrip.
So as to do that I added the following field to WP_Term
:
'children' => [
'type' => new ListOfType($this->getTerm()),
'description' => 'retrieves children of the term',
'resolve' => function($root, $args) {
$childrenIds = get_term_children($root->term_id, $root->taxonomy);
return get_terms($root->taxonomy, array('include' => $childrenIds));
}
]
Unfortunately, it does not work and I do not why. There is no any error in logs. In Chromeiql I receive only:
TypeError: Failed to fetch
at TypeError (native)
Do you know maybe why?
Did you have such problems? How did you resolve them?
Cheers.
Be compatible with PHP 5.6
There are three instances where graphql-wp uses the ?? operator that could be replaced by ?: in order to be compatible with PHP 5.6 instead of PHP 7:
WPType.php, line 10
Type/Definition/WPPost.php, line 18
Type/Definition/Term.php, line 18
Otherwise I get the following error in the server logs when trying to access the graphql endpoint:
AH01071: Got error 'PHP message: PHP Parse error: syntax error, unexpected '?' in ...snip.../wp-content/plugins/graphql-wp/Type/Definition/WPTerm.php on line 18\n'
fatal error on activation (back again with another issue)
Hey! thanks for this plugin! unfortunately i cannot activate the plugin from wp admin when i try to activate:
Plugin could not be activated because it triggered a fatal error.
Fatal error: Class 'TheFold\WordPress\Dispatch' not found in /this/is/my/path/folder/bedrock/web/app/plugins/graphql-wp/index.php on line 21
it's the first time i'm using composer, so maybe i did some misconfiguration.
i installed bedrock as advised. then inside the main dir of the new project i did:
composer require mohiohio/graphql-wp
i can find the plugin correctly and the folders in vendor (thefold is all lowercase).
thanks for your help
Apollo and Relay Modern compatibility
Is this plugin compatible with both Apollo and Relay Modern?
Problem with custom post type query
Heyho its me toni again, new account :P
when i call a query { wp_query { posts(post_type: "offers") { title } } } i get the following error.
"message": "Abstract type WPPost must resolve to an Object type at runtime for field WPQuery.posts with value "WP_Post Object\n(\n [ID] => 11\n [post_author] => 1\n [post_date] => 2017-05-04 15:04:18\n [post_date_gmt] => 2017-05-04 13:04:18\n [post_content] =>
- \r\n \t
- Wir sind die Bulletlist für dieses Angebot \r\n \t
- Wir sind die Bulletlist für dieses Angebot \r\n \t
- Wir sind die Bulletlist für dieses Angebot \r\n \t
- Wir sind die Bulletlist für dieses Angebot \r\n \t
- Wir sind die Bulletlist für dieses Angebot \r\n
Advanced custom fields - repeater - galleries and flexible content
Are the re some hints how to integrate those fieldtypes into our graphql schema or somebody has already done that?
Example Query doesn't work, seems like some of the schema isn't being included?
query example { wp_query { posts(paged: 1, posts_per_page: 10) { title name terms(taxonomy: "category") { name slug } } } }
returns the following errors:
{ "errors": [ { "message": "Unknown argument \"paged\" on field \"posts\" of type \"WPQuery\".", "category": "graphql", "locations": [ { "line": 3, "column": 10 } ] }, { "message": "Unknown argument \"posts_per_page\" on field \"posts\" of type \"WPQuery\".", "category": "graphql", "locations": [ { "line": 3, "column": 20 } ] }, { "message": "Cannot query field \"title\" on type \"WPPostConnection\".", "category": "graphql", "locations": [ { "line": 4, "column": 6 } ] } ] }
I can see the types are defined inside the plugin, but for some reason, they dont' seem to be registered?
PHP Fatal error: Uncaught Error: Class 'Mohiohio\GraphQLWP\Schema' not found in /app/public/wp-content/plugins/graphql-wp-master/index.php:63
line in question: $schema = Schema::build();
I had installed the plugin, ran composer to include the vendor dependencies.
Plugin could not be activated because it triggered a fatal error.
Hi @tim-field ,
Maybe, I am doing something wrong, but I cannot activate the plugin mohiohio/graphql-wp
. I receive the following error during activation:
Plugin could not be activated because it triggered a fatal error.
( ! ) Fatal error: Class 'Mohiohio\WordPress\Router' not found in /var/www/html/wordpress/wp/wp-content/plugins/graphql-wp/index.php on line 18
Call Stack
# Time Memory Function Location
1 0.2004 243384 {main}( ) .../plugins.php:0
2 0.2900 2458632 plugin_sandbox_scrape( ) .../plugins.php:155
3 0.2901 2459376 include( '/var/www/html/wordpress/wp/wp-content/plugins/graphql-wp/index.php' ) .../plugins.php:153
I tried two methods of Wordpress installation: manual and through composer.
I tried also two methods of storing vendor
folder: inside and outside Wordpress.
Nothing works for me. Do you know what might be the problem?
A regular WP plugin
Hey Tim, Just wondering if you're planning to release it as a regular WordPress plugin with its dependencies etc. packaged as a normal WP plugin?
Plugins needs new contributor
If theres nothing ongoing progress i would like to take ownership on this plugin and maintain it in the future, because i make a lot of etension like advanced custom fields extension and integrating custom post type calls by default. Plus i'm working on tutorials how to use this plugin for headless systems with vue.js. So please keep me informed if this is possbile.
Returning children for pages
How can we retrieve Page children?
Version for Nginx
I might do something improperly, but /graphql
endpoint returns 404 on Nginx.
Everything works ok on Apache2.
Do you receive also 404 on Nginx?
Taxonomy Parameters?
First, thanks for such useful and wonderful plugin!
Do you have plans to add Taxonomy Parameters for wp_query?
I tried to add this possibility, but fails to make the data type needed for wordpress.
$args = array(
'post_type' => 'post',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'movie_genre',
'field' => 'slug',
'terms' => array( 'action', 'comedy' ),
),
array(
'taxonomy' => 'actor',
'field' => 'term_id',
'terms' => array( 103, 115, 206 ),
'operator' => 'NOT IN',
),
),
);
Failing OPTIONS requests
I found that my GraphQL client is sending OPTIONS type requests before every request which silently produces an error.
I think the server endpoint should respond to these requests.
Returning the error:
{"errors":{"message":"Wrong query format or empty query. Either send raw query _with_ Content-Type: 'application\/json' header or send query by posting www-form-data with a query=\"query{}...\" parameter"}}
I'd look into the server code myself but I'm not especially crafty with PHP 😜
Cannot install properly
Hi there,
i followed the step in the readme:
composer require mohiohio/graphql-wp
i can see the lib and all the dependencies in my "vendor" folder. i also added the entries proposed to my "composer.json" with the installer-paths for the plugins.
but even after a re-install, i can't see any entries to my "wp-content/plugins" folder - also no "/graphql" endpoint is there when i startup.. but ok i guess the basic install of the plugin into wordpress is missing..
how should this work properly?
Problem with /graphql endpoint
Hi @timbofield
I tried to use your project and installed Wordpress together with your package via composer.
Unfortunately, there is no endpoint as: /graphql
Could you describe how I should install it?
Cheers.
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.