Wordpress wrapper to expose Carbon Fields to WpGraphQL queries.

Overview

WpGraphQLCrb

A Wordpress wrapper to expose Carbon Fields to WpGraphQL queries.

Important

This is just the first version. There is a lot of work to be done. This packages exposes all the fields of the container, if the container type is post_meta, term_meta, user_meta, comment_meta or theme_options.

Note: This is a very experimental version, so it is probably shipped with bugs.

Usage

  1. First you have to install Carbon Fields and WpGraphQL.
  2. Then install this package via packagist: composer require matepaiva/wp-graphql-crb
  3. Wrap every Carbon Field container that you want to expose via GraphQL with the static method WpGraphQLCrb\Container::register. For example:
  <?php

  use WpGraphQLCrb\Container as WpGraphQLCrbContainer;
  use Carbon_Fields\Container\Container;
  use Carbon_Fields\Field\Field;

  WpGraphQLCrbContainer::register(
    Container::make('term_meta', __('Custom Data', 'app'))
      ->where('term_taxonomy', '=', 'category')
      ->add_fields([
        Field::make('image', 'crb_img')
          ->set_value_type('url')
      ])
  );
  1. Now the query below will work:
{
  categories {
    edges {
      node {
        id
        crb_img
      }
    }
  }
}

About Theme Options

Theme options are not part of any structure already known by Wordpress, so it has its own root. Every theme_options fields will be displayed in GraphQL as direct children of crb_ThemeOptions. Be carefull about name collision.

Comments
  • Fatal error on fresh install when using a post_meta container

    Fatal error on fresh install when using a post_meta container

    I get an error on a fresh install of this package in my plugin. I never used to, the only thing I've done is upgraded WP GraphQL to 1.2.5. In GraphiQL, I get:

    {
      "code": "internal_server_error",
      "message": "<p>There has been a critical error on this website.</p><p><a href=\"https://wordpress.org/support/article/debugging-in-wordpress/\">Learn more about debugging in WordPress.</a></p>",
      "data": {
        "status": 500
      },
      "additional_errors": []
    }
    

    Inspecting the debug log, I see:

    [08-Mar-2021 15:00:46 UTC] PHP Notice:  Undefined property: WP_Post_Type::$graphql_single_name in /var/www/html/wpgraphql_crb_test/wp-content/plugins/graphql-carbon-test/vendor/matepaiva/wp-graphql-crb/src/Container.php on line 203
    [08-Mar-2021 15:00:46 UTC] PHP Notice:  Undefined property: WP_Post_Type::$graphql_single_name in /var/www/html/wpgraphql_crb_test/wp-content/plugins/graphql-carbon-test/vendor/matepaiva/wp-graphql-crb/src/Container.php on line 203
    [08-Mar-2021 15:00:46 UTC] PHP Notice:  Undefined property: WP_Post_Type::$graphql_single_name in /var/www/html/wpgraphql_crb_test/wp-content/plugins/graphql-carbon-test/vendor/matepaiva/wp-graphql-crb/src/Container.php on line 203
    [08-Mar-2021 15:00:46 UTC] PHP Notice:  Undefined property: WP_Post_Type::$graphql_single_name in /var/www/html/wpgraphql_crb_test/wp-content/plugins/graphql-carbon-test/vendor/matepaiva/wp-graphql-crb/src/Container.php on line 203
    [08-Mar-2021 15:00:46 UTC] PHP Notice:  Undefined property: WP_Post_Type::$graphql_single_name in /var/www/html/wpgraphql_crb_test/wp-content/plugins/graphql-carbon-test/vendor/matepaiva/wp-graphql-crb/src/Container.php on line 203
    [08-Mar-2021 15:00:46 UTC] PHP Notice:  Undefined property: WP_Post_Type::$graphql_single_name in /var/www/html/wpgraphql_crb_test/wp-content/plugins/graphql-carbon-test/vendor/matepaiva/wp-graphql-crb/src/Container.php on line 203
    [08-Mar-2021 15:00:46 UTC] PHP Notice:  Undefined property: WP_Post_Type::$graphql_single_name in /var/www/html/wpgraphql_crb_test/wp-content/plugins/graphql-carbon-test/vendor/matepaiva/wp-graphql-crb/src/Container.php on line 203
    [08-Mar-2021 15:00:46 UTC] PHP Fatal error:  Uncaught TypeError: Argument 1 passed to register_graphql_field() must be of the type string, null given, called in /var/www/html/wpgraphql_crb_test/wp-content/plugins/graphql-carbon-test/vendor/matepaiva/wp-graphql-crb/src/Container.php on line 47 and defined in /var/www/html/wpgraphql_crb_test/wp-content/plugins/wp-graphql/access-functions.php:269
    Stack trace:
    #0 /var/www/html/wpgraphql_crb_test/wp-content/plugins/graphql-carbon-test/vendor/matepaiva/wp-graphql-crb/src/Container.php(47): register_graphql_field()
    #1 /var/www/html/wpgraphql_crb_test/wp-content/plugins/graphql-carbon-test/vendor/matepaiva/wp-graphql-crb/src/Container.php(63): WpGraphQLCrb\Container->registerField()
    #2 /var/www/html/wpgraphql_crb_test/wp-content/plugins/graphql-carbon-test/vendor/matepaiva/wp-graphql-crb/src/Container.php(57): WpGraphQLCrb\Container->registerFields()
    #3 /var/www/html/wpgraphql_crb_test/wp-includes/class-wp-hook.php(287): WpGraphQLCrb\Container->graphqlRegisterTypes()
    #4 /var/www/html/wpgraphql_crb_test/wp-inclu in /var/www/html/wpgraphql_crb_test/wp-content/plugins/wp-graphql/access-functions.php on line 269
    

    And digging deeper, I find that for the WpGraphQLCrb\Container instance, the getGraphQLRoot() method is returning:

    Array
    (
        [0] => post
        [1] => page
        [2] => mediaItem
        [3] => 
        [4] => 
        [5] => 
        [6] => 
        [7] => 
        [8] => 
        [9] => 
    )
    

    This array is mapped from Carbon_Fields\REST_API\Decorator::get_post_meta_container_settings() using the map function $type -> getGraphQLPostTypeRoot($type). The array provided from that mapping is:

    Array
    (
        [0] => post
        [1] => page
        [2] => attachment
        [3] => revision
        [4] => nav_menu_item
        [5] => custom_css
        [6] => customize_changeset
        [7] => oembed_cache
        [8] => user_request
        [9] => wp_block
    )
    

    So it seems that Container->getGraphQLPostTypeRoot($type) is failing for revision, nav_menu_item, custom_css... etc, as those post type objects don't have a graphql_single_name.

    My composer json:

    {
        "require": {
            "htmlburger/carbon-fields": "^3.2",
            "matepaiva/wp-graphql-crb": "dev-master"
        },
        "minimum-stability": "dev",
        "prefer-stable": true
    }
    

    Installed plugins: WP GraphQL (Version 1.2.5)

    My code:

    <?php
    /*
    Plugin Name: WPGraphQL Carbon Fields Test
    Version: 1.0
    */
    
    namespace GraphQLCarbonTest;
    
    use WpGraphQLCrb\Container as WpGraphQLCrbContainer;
    use Carbon_Fields\Container;
    use Carbon_Fields\Field;
    
    add_action( 'carbon_fields_register_fields', 'GraphQLCarbonTest\crb_attach_theme_options' );
    function crb_attach_theme_options() {
    	WpGraphQLCrbContainer::register(
        Container::make( 'post_meta', __( 'Test Post Meta Container' ) )
            ->add_fields( array(
                Field::make( 'text', 'crb_text', 'Text Field' ),
                // Field::make( 'icon', 'sm_download_icon', __( 'Icon', 'crb' ) ),
            ) )
    	);
    }
    
    add_action( 'after_setup_theme', 'GraphQLCarbonTest\crb_load' );
    function crb_load() {
        require_once( 'vendor/autoload.php' );
        \Carbon_Fields\Carbon_Fields::boot();
    }
    

    I'm thinking that removing these types from the $roots whose post type objects don't have a graphql_single_name would solve the issue, but I'm not confident that it wouldn't break anything else. What do you think?

    opened by moxxuk 11
  • Graphql Error on association field with custom post type or taxonomy if it has multiple types.

    Graphql Error on association field with custom post type or taxonomy if it has multiple types.

    I've a association field with a custom subtype and multiple types, like this:

    Field::make('association', 'test', __('Materials:'))
        ->set_types(
            array(
                array(
                    'type'      => 'post',
                    'post_type' => 'materials',
                ),
                array(
                    'type'      => 'term',
                    'taxonomy' => 'material_category'
                )
            )
        )
    

    If the graphql_single_name option (from the post type or taxonomy) not starts with an uppercase letter, it results in a graphql error: Type loader is expected to return type "materialCategory", but it returned "MaterialCategory".

    I took a look at it and saw that register_graphql_union_type function, triggers a prepare_type function that uses ucfirst for the type name. The following fix works for me.

    diff --git a/src/Field.php b/src/Field.php
    index 0ea53e9..b1a9bf6 100644
    --- a/src/Field.php
    +++ b/src/Field.php
    @@ -193,7 +193,7 @@ private function getTypeFromAssociation()
                 return 'Post';
               }
     
    -          return $graphql_single_name;
    +          return ucfirst($graphql_single_name);
             }
     
             if ($object instanceof Term) {
    @@ -206,7 +206,7 @@ private function getTypeFromAssociation()
                 return 'Tag';
               }
     
    -          return $taxonomy_name;
    +          return ucfirst($taxonomy_name);
             }
     
             if ($object instanceof Comment) {
    
    opened by benada002 9
  • Error: Type Crb_ThemeOptions must define one or more fields.

    Error: Type Crb_ThemeOptions must define one or more fields.

    Hi,

    If I try to run GraphQL Code Generator, I get the following error: Type Crb_ThemeOptions must define one or more fields.

    I think one possible solution would be:

    diff --git a/src/Container.php b/src/Container.php
    index aaee152..284437e 100644
    --- a/src/Container.php
    +++ b/src/Container.php
    @@ -21,6 +21,8 @@ class Container
     {
       private static $is_first_time = true;
     
    +  private static $is_first_time_theme_options = true;
    +
       public function __construct(CrbContainer $container)
       {
         $this->container = $container;
    @@ -54,6 +56,12 @@ public function graphqlRegisterTypes()
           Container::$is_first_time = false;
           Container::registerStaticObjectTypes();
         }
    +
    +    if ($this->container->type === 'theme_options' && Container::$is_first_time_theme_options) {
    +      Container::$is_first_time_theme_options = false;
    +      Container::registerStaticThemeOptionObjectTypes();
    +    }
    +
         $this->registerFields();
       }
     
    @@ -64,12 +72,14 @@ private function registerFields()
         }
       }
     
    -  static function registerStaticObjectTypes()
    +  static function registerStaticThemeOptionObjectTypes()
       {
    -    register_graphql_object_type('Crb_ThemeOptions', [
    -      'description' => \__("All the Carbon Field Theme Options", 'app'),
    -      'fields' => [],
    -    ]);
    +    register_graphql_object_type(
    +        'Crb_ThemeOptions', [
    +        'description' => \__("All the Carbon Field Theme Options", 'app'),
    +        'fields' => [],
    +      ]
    +    );
     
         register_graphql_field(
           'RootQuery',
    @@ -81,7 +91,10 @@ static function registerStaticObjectTypes()
             }
           ]
         );
    +  }
     
    +  static function registerStaticObjectTypes()
    +  {
         register_graphql_object_type('Crb_Select', [
           'description' => \__("The selected option/radio", 'app'),
           'fields' => [
    

    Or do you've another idea?

    opened by benada002 5
  • Issue: Theme options in WPGraphQL with Carbon Fields

    Issue: Theme options in WPGraphQL with Carbon Fields

    Hello! I've decided to use your plugin along with Carbon fields (v. 3.2) and WPGraphQL. Unfortunately the theme_options field doesn't show up in the GraphQL IDE in my wordpress (v. 5.6). My theme options container looks like this:

    WpGraphQLCrbContainer::register(
        Container::make( 'theme_options', __( 'Theme Options' ) )
            ->add_tab( 'Footer', [
                Field::make( 'text', 'footer_text', 'Footer text' ),
            ] )
    );
    

    Adding ->set_visible_in_rest_api(true) didn't change anything. Is this something expected, maybe you can help me with this problem?

    Kind regards, Jakub.

    enhancement 
    opened by tysian 4
  • Only scalar fields are supported in Theme Options

    Only scalar fields are supported in Theme Options

    I tried getting a complex field from a theme option, but I get an error in Container.php line 176 that the callback expected 6 arguments but was passed 3.

    Only the getScalar resolver seems to accept only three arguments, so I guess this is a bug?

    opened by ojohnny 2
  • Installing via packagist results in 'minimum-stability' error.

    Installing via packagist results in 'minimum-stability' error.

    Following the 'Usage' in the readme, and installing the package using the following:

    composer require matepaiva/wp-graphql-crb

    ...I am faced with the following:

    Could not find a version of package matepaiva/wp-graphql-crb matching your minimum-stability (stable). Require it with an explicit version constraint allowing its desired stability.
    

    What is the recommended way to install?

    opened by moxxuk 2
  • add support to return html when rich_text carbon fields

    add support to return html when rich_text carbon fields

    Before this commit, a carbon field type rich_text when queried via graphql would return a string like:

    first paragraph
    \r\n\r\n
    second paragraph
    

    From now on, it will return a HTML parsed string:

    <p>first paragraph</p>
    \n
    <p>second paragraph</p>
    
    opened by matepaiva 1
  • Error when using Carbon Map field

    Error when using Carbon Map field

    Hey, I'm trying to work with Map carbon field, but when use wpgraphql to retrieve the value it returns an error, because it expects string, but the returned value from map field is array with 5 items (value, lat, lng, zoom, address).

    Field::make('map', 'location', __('Location', 'crb'));

    I could use graphql_resolve_field filter to return $result['value'] as a string. In my case (where the field name is 'location') I can not choose nested nodes (value, lat, lng, zoom or address), I have just "location".

    opened by plamenradev 0
  • discussion: Contiditional Fields

    discussion: Contiditional Fields

    I was thinking in a good semantic way of matching Conditional Fields with GraphQL. Something like that:

    {
      institutionalContents {
        nodes {
          title
          excerpt
          action { # this name comes from set_conditional_logic.field 
            ... on NewsletterSubscribeAction { # this name comes from set_conditional_logic.value + set_conditional_logic.field
              textFieldPlaceholder
              textFieldLabel
              buttonText
            }
            ... on LinkAction {
              href
              label
            }
          }
        }
      }
    }
    

    The idea is using Inline Fragments, grouping fields with the same set_conditional_logic within the same Carbon Container. I don't know if it is a good idea so I want to know your opinion. In the case above, the carbon fields would be something like that:

          Field::make('select', 'action', 'Ação')->set_options([
            'link' => 'Link',
            'newsletter_subscribe' => 'Newsletter Subscribe',
          ]),
          
          // Link
          Field::make('text', 'href', 'href')->set_conditional_logic([['field' => 'action', 'value' => 'link']]),
          Field::make('text', 'label', 'label')->set_conditional_logic([['field' => 'action', 'value' => 'link']]),
    
          // Newsletter Subscribe
          Field::make('text', 'text_field_label', 'text_field_label')->set_conditional_logic([['field' => 'action', 'value' => 'newsletter_subscribe']]),
          Field::make('text', 'text_field_placeholder', 'text_field_placeholder')->set_conditional_logic([['field' => 'action', 'value' => 'newsletter_subscribe']]),
          Field::make('text', 'button_text', 'button_text')->set_conditional_logic([['field' => 'action', 'value' => 'newsletter_subscribe']]),
    

    Please have a look @Mooxdesign @ojohnny @moxxuk @benada002 :)

    opened by matepaiva 7
Releases(0.0.6)
Owner
Matheus Paiva
Matheus Paiva
Enable query locking for WPGraphQL by implementing persisted GraphQL queries.

?? WP GraphQL Lock This plugin enables query locking for WPGraphQL by implementing persisted GraphQL queries. Persisted GraphQL queries allow a GraphQ

Valu Digital 21 Oct 9, 2022
WPGraphQL Extension: Adds "meta_query" support to postObject connection queries using WP_Query

WPGraphQL Meta Query This plugin adds Meta_Query support to the WP GraphQL Plugin for postObject query args. Why is this an extension and not part of

WPGraphQL 42 Nov 10, 2022
[ALPHA] Implementation of persisted queries for WPGraphQL

WPGraphQL Persisted Queries Persisted GraphQL queries allow a GraphQL client to optimistically send a hash of the query instead of the full query; if

Quartz 18 Jun 20, 2022
WPGraphQL Polylang Extension for WordPress

WPGraphQL Polylang Extension Extend WPGraphQL schema with language data from the Polylang plugin. Features For posts and terms (custom ones too!) Adds

Valu Digital 102 Dec 29, 2022
a wordpress plugin that improves wpgraphql usage together with wpml

WPGraphQL WPML Extension Contributors: rburgst Stable tag: 1.0.6 Tested up to: 5.6.1 Requires at least: 4.9 Requires PHP: 7.0 Requires WPGraphQL: 0.8.

null 42 Dec 15, 2022
Querycase provides a convenient, fluent interface for creating and running database queries in WordPress.

Querycase database for WordPress Dependency-free library to create SQL Queries in WordPress. Explore the documentation → ℹ️ About Querycase Querycase

Alessandro Tesoro 7 Oct 17, 2021
Authentication for WPGraphQL using JWT (JSON Web Tokens)

WPGraphQL JWT Authentication This plugin extends the WPGraphQL plugin to provide authentication using JWT (JSON Web Tokens) JSON Web Tokens are an ope

WPGraphQL 268 Dec 31, 2022
Send emails via mutation using WpGraphQl

WPGraphQL Send Email Plugin One of the simple things about a traditional WordPress sites is sending emails, this plugin makes it easy to do this via a

Ashley Hitchcock 18 Aug 21, 2022
An WPGraphQL extension that adds SearchWP's query functionality to the GraphQL server

QL Search What is QL Search? An extension that integrates SearchWP into WPGraphQL. Quick Install Install & activate SearchWP v3.1.9+ Install & activat

Funkhaus 11 May 5, 2022
Structured content blocks for WPGraphQL

WPGraphQL Content Blocks (Structured Content) This WPGraphQL plugin returns a WordPress post’s content as a shallow tree of blocks and allows for some

Quartz 72 Oct 3, 2022
Adds Settings to the Custom Post Type UI plugin to show Post Types in WPGraphQL

DEPRECATION NOTICE ?? Custom Post Type UI v1.9.0 introduced formal support for WPGraphQL!!! ?? With that, this plugin is being deprecated and will no

WPGraphQL 77 Aug 3, 2022
WPGraphQL FacetWP integration plguin

WPGraphQL-FacetWP: WPGraphQL provider for FacetWP Quick Install Download and install like any WordPress plugin. Documentation The WPGraphQL documentat

null 31 Dec 11, 2022
WPGraphQL for Meta Box

WPGraphQL-MetaBox: WPGraphQL provider for Meta Box Quick Install Download and install like any WordPress plugin. Documentation The WPGraphQL documenta

null 25 Aug 8, 2022
This is an extension to the WPGraphQL plugin for Yoast SEO

WPGraphQl Yoast SEO Plugin Please note version 14 of the Yoast Plugin is a major update. If you are stuck on version of Yoast before V14 then use v3 o

Ashley Hitchcock 197 Dec 26, 2022
Add WooCommerce support and functionality to your WPGraphQL server

WPGraphQL WooCommerce (WooGraphQL) Docs • AxisTaylor • Join Slack Quick Install Install & activate WooCommerce Install & activate WPGraphQL Download t

WPGraphQL 546 Jan 2, 2023
Gutenberg Custom Fields... wait what?

Gutenberg Custom Fields Gutenberg Custom Fields allows you to control the content of the Gutenberg edit screen by creating pre-filled templates. Navig

Riad Benguella 192 Dec 24, 2022
Adds `tax_query` support to postObject connection queries using WP_Query

WPGraphQL Tax Query This plugin adds Tax_Query support to the WP GraphQL Plugin for postObject query args (WP_Query). Pre-req's Using this plugin requ

WPGraphQL 39 Dec 2, 2022
A custom WordPress nav walker class to fully implement the Twitter Bootstrap 4.0+ navigation style (v3-branch available for Bootstrap 3) in a custom theme using the WordPress built in menu manager.

WP Bootstrap Navwalker This code in the main repo branch is undergoing a big shakeup to bring it in line with recent standards and to merge and test t

WP Bootstrap 3.3k Jan 5, 2023
A curated list of Awesome WordPress Theme, Plugins and Framework development Resources and WordPress Communities.

Awesome WordPress A curated list of Awesome WordPress Theme, Plugins and Framework development Resources and WordPress Communities. Inspired by bayand

Dropndot Limited 91 Dec 26, 2022