wp-graphql-woocommerce icon indicating copy to clipboard operation
wp-graphql-woocommerce copied to clipboard

Add custom field to mutation

Open brokieb opened this issue 2 years ago • 5 comments

Is your feature request related to a problem? Please describe. Some customers wan't to add TAX number to order.

Describe the solution you'd like I wan't add taxNumber field to CustomerAddressInput, and after fill this field in mutation, this data is not saved

Additional context

add_filter('graphql_input_fields', function($input_fields, $type_name) {
    if ($type_name === "CustomerAddressInput") {
        $input_fields['vatNumber'] = [
            'type' => 'String',
            'description' => __('vat number field.', 'wp-graphql'),
        ];
    }

    return $input_fields;
}, 10, 2);

brokieb avatar Jun 21 '22 07:06 brokieb

@brokieb This can be done by doing register_graphql_field() on CustomerAddressInput. This will register this field to the GraphQL schema. Next you can hook into a filter like this one to add it to the order.

kidunot89 avatar Jun 22 '22 22:06 kidunot89

@kidunot89 I trying to add filter but hook graphql_woocommerce_after_order_create does not working when I add new order.

add_filter('graphql_woocommerce_after_order_create', 'add_vat_number', 4);
function add_vat_number($order, $input, $context, $info){

	update_post_meta( $order->id, '_vat_number', sanitize_text_field(123123) );
	return 1;
}

jensej avatar Jul 12 '22 14:07 jensej

@jensej your code has some errors. Use order->get_id() not order->id.

kidunot89 avatar Jul 12 '22 15:07 kidunot89

@jensej your code has some errors. Use order->get_id() not order->id.

@kidunot89 nothing has changed, looks like the hook won't turn on

jensej avatar Jul 12 '22 15:07 jensej

@jensej What mutation are you running?

kidunot89 avatar Jul 13 '22 23:07 kidunot89

@kidunot89 Hello, I'm also struggling with the same thing with the checkout mutation. I don't have any previous wordpress experience and can't seem to work out how the ecosystem works and where to write these hooks. It would be really helpful if you could reference me some guides.

Edit:

I added this to 'functions.php' in the '/includes' folder of the plugin and it seems to be working, am I missing something?

add_action( 'graphql_register_types', function() {
  register_graphql_field( 'CustomerAddressInput', 'CUSTOM_FIELD', [
    'type' => 'String',
  ]);
} );

add_filter('graphql_woocommerce_after_checkout', function ($order, $input, $context, $info){
	update_post_meta( $order->get_id(), 'CUSTOM_FIELD', $input['billing']['CUSTOM_FIELD'] );
	return null;
}, 10, 4);

johnakisk0700 avatar Oct 24 '22 08:10 johnakisk0700

@johnakisk0700 @brokieb You should be using WC DataStore functions not WP Meta functions. Try

$order->update_meta_data( 'CUSTOM_FIELD', $input['billing']['CUSTOM_FIELD'] );
$order->save();

kidunot89 avatar Feb 07 '23 13:02 kidunot89