PHP code example of thefold / graphql-wp

1. Go to this page and download the library: Download thefold/graphql-wp library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

thefold / graphql-wp example snippets


// 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;
});

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()
    ]);
});