1

I am using GraphQL in Wordpress as API with this plugin: https://docs.wpgraphql.com/getting-started/custom-fields-and-meta I created custom field and I want to use where clause for boolean attribute but I get all record even those who dont match my where clause

My query looks like this:

    query pagesInMenu {
 pages(where: { menu: true }) {
    edges {
      node {
        id
        menu
        title
      }
    }
  }
}

And I get records where menu = false and menu = true ... It is custom field added via PHP code below:

function registerMenu($type) {
    register_graphql_field( $type, 'menu', [
        'type' => 'Boolean',
        'description' => __( 'Is in menu?', 'wp-graphql' ),
        'resolve' => function( $post ) {
            $menu = get_post_meta( $post->ID, 'menu', true );
            return ! empty( $menu ) ? ($menu == "true") : false;
        }
    ] );
}

add_action( 'graphql_register_types', registerMenu('Page') );
add_action( 'graphql_register_types', registerMenu('RootQueryToPageConnectionWhereArgs') );
frankV
  • 5,353
  • 8
  • 33
  • 46
  • I'd try `filter_var(...)` instead of that comparison; that is `return filter_var($menu, FILTER_VALIDATE_BOOLEAN);` – Miro Hudak Apr 10 '19 at 15:55
  • @MiroHudak I changed as you recommended the PHP code, now I get still all records but theres menu: false everywhere, I am very new in this problematics, I tried some changes with that return statement but no luck so far. :( – Kryštof Košut Apr 10 '19 at 16:04
  • @KryštofKošut did you ever solve this? I ran into the same issue tonight. – frankV Jan 02 '22 at 07:05

1 Answers1

0

A few things are incorrect here:

  1. WordPress Actions: You are supposed to pass a callable (i.e. the function function name ) that accepts the arguments passed by the action itself, and not whatever you come up with.
  2. GraphQL connection where args shouldnt have a resolver on the field. The user provides a value, and then the ConnectionResolver sets the args to the query, using graphql_connection_query_args or something similar.

This is what your provided should look like on a basic level:

function register_menu() {
  register_graphql_field( 
    'Page',
    'isInMenu',
    [
      'type' => 'Boolean',
      'description' => __( 'Is in menu?', 'wp-graphql' ),
      'resolve' => function( $post ) {
          $menu = get_post_meta( $post->ID, 'menu', true );
          return ! empty( $menu );
        }
    ]
  );

  register_graphql_field(
    'RootQueryToPageConnectionWhereArgs'
    'showInMenu'
    [
      'type' => 'Boolean',
      'description' => __( 'Filter results by whether page is in a menu', 'my-plugin' ),
    ]
  );
}

add_action( 'graphql_register_types', 'register_menu' );
Dovid Levine
  • 167
  • 1
  • 4
  • 14