Search code examples
wordpresswp-graphql

Querying custom term_meta field using WPGraphQL returns an empty field for that term


I have a custom color field in the wp_termmeta table for my wordpress theme tags. The values are saved in the database fine. However I have issues registering it with the WPGQL plugin - when I run the query, it always comes back empty:

   {
     "node": {
     "name": "Арт",
     "tagColor": ""
   }

I'm trying to register it with the WPGraphQL plugin like so:

 add_action( 'graphql_register_types', function() {
     register_graphql_field( 'Tag', 'tagColor', [
        'type' => 'String',
        'description' => __( 'Tag color', 'wp-graphql' ),
        'resolve' => function(  $term ) {
          $tagColor = get_term_meta( "$term->ID", 'color', true );
          return ! empty( $tagColor ) ? $tagColor : '';
        }
     ] );
  } );


Solution

  • Not sure how much help this is 4 months later but maybe this will help future peeps, $term->ID is actually incorrect.

    To debug you can return print_r($term, true) this will print out whats in the object.

    $term->ID is actually the graphql id you want $term->term_id to get the Wordpress database id.

    Also want to remove the qoutes from $term->term_id

    get_term_meta($term->term_id, 'color', TRUE);