Add custom order item meta data - woocommerce

I am currently working on some code that will run with the woocommerce_order_status_completed hook. The code will connect to a 3rd party to retrieve a serial number for the purchased item. Originally I was planning on just emailing the serial to the customer, but I was wondering, would it be possible to add the retrieved serial number to the ordered item (meta?) so that when the customer goes to their account page to view the order, they see the serial number listed there (under the product(s) that was purchased?
Is this possible some how? Add information to the order to be shown in the account page?

Sure, add it like this:
function add_order_item_meta($item_id, $values) {
$key = ''; // Define your key here
$value = ''; // Get your value here
woocommerce_add_order_item_meta($item_id, $key, $value);
}
add_action('woocommerce_add_order_item_meta', 'add_order_item_meta', 10, 2);

If you are using Class:
add_action( 'woocommerce_add_order_item_meta', array( $this,'add_order_item_meta'), 10, 2 );
public static function add_order_item_meta($item_id, $values) {
$key = 'statusitem'; // Define your key here
$value = 'AAA'; // Get your value here
wc_update_order_item_meta($item_id, $key, $value);
}
if not using class:
add_action( 'woocommerce_add_order_item_meta', 'add_order_item_meta', 10, 2 );
function add_order_item_meta($item_id, $values) {
$key = 'statusitem'; // Define your key here
$value = 'AAA'; // Get your value here
wc_update_order_item_meta($item_id, $key, $value);
}
Json response call from API, look at meta_data :
"line_items": [{
"id": 425,
"name": "FANTA",
"product_id": 80,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "30000.00",
"subtotal_tax": "0.00",
"total": "30000.00",
"total_tax": "0.00",
"taxes": [],
"meta_data": [{
"id": 3079,
"key": "statusitem",
"value": "AAA"
}],
"sku": "000000000000009",
"price": 30000
}],

Related

Wordpress + Vimeo API | Find Specific Video Via URI

So I am trying to utilize the Vimeo API in Wordpress to automatically embed a specific video, but the information I will have available is the URI. I created the following call in Postman which retrieves what I need, but I am struggling with how to authenticate via token to get this in Wordpress. I have a custom field in the post type that is "Vimeo URI" and want to use that in the call. Here is what I have in Postman:
GET https://api.vimeo.com/videos?fields=uri,name,link&uris={VIDEOURI}
That returns (data replaced):
{
"total": 1,
"page": 1,
"per_page": 25,
"paging": {
"next": null,
"previous": null,
"first": "/videos?fields=uri%2Cname%2Clink&uris=%2Fvideos%2F441653190&page=1",
"last": "/videos?fields=uri%2Cname%2Clink&uris=%2Fvideos%2F441653190&page=1"
},
"data": [
{
"uri": "VIDEO URI",
"name": "VIDEO NAME",
"link": "VIDEO URL"
}
]
}
Here is how I started the request in functions.php:
$uri = the_field( 'vimeo_uri' );
$args_for_get = array(
'headers' => array(
'Authorization' => 'bearer INSERTED MY TOKEN HERE'
),
'fields' => 'uri,name,link',
'uri' => $uri
);
$url = 'https://api.vimeo.com/videos';
$request = wp_remote_get( $url, $args_for_get );
return load_request($request);
function load_request($response) {
try {
$json = json_decode( $response['body'] );
} catch ( Exception $ex ) {
$json = null;
}
return $json;
}
$json->data->link = $vimeolink;
This comes back with 400 bad request from Vimeo. Would appreciate any help on getting this to work. Also, should I be architecting this differently? The idea is for this call to go out on page load for each post that has the URI field, but maybe I should be scraping the data to a plugin instead and then retrieving the data from there?

How to get custom post meta in wp media js

I have a custom post type and on the admin edit post screen I'm using wp.media to attach the track to the post. And I'm attaching some post meta to that track also.
Is there easy way to force wp.media JS returns track with meta data?
trackMediaUploader = wp.media.frames.file_frame = wp.media( { ... } );
trackMediaUploader.on( 'select', () => {
const attachment = trackMediaUploader.state().get( 'selection' ).first().toJSON();
// want to get post meta of this attachment
console.log( attachment );
});
I've tried to use wp_get_attachment_metadata filter, but it's wont works with wp.media js:
function add_attachment_metadata( $data, $id ) {
$lyrics = get_post_meta( $id, '_track_lyrics', true );
if( $lyrics ) {
$data[ 'track-lyrics' ] = $lyrics;
}
return $data;
}
You can use wp_prepare_attachment_for_js hook:
add_filter( 'wp_prepare_attachment_for_js', 'prepare_attachment_for_js', 10, 3 );
function prepare_attachment_for_js( $response, $attachment, $meta ) {
$response[ 'trackLyrics' ] = get_post_meta( $attachment->ID, '_track_lyrics', true );
return $response;
}
// in admin js:
trackMediaUploader = wp.media.frames.file_frame = wp.media( { ... } );
trackMediaUploader.on( 'select', () => {
const attachment = trackMediaUploader.state().get( 'selection' ).first().toJSON();
console.log( attachment.trackLyrics );
});

Passing Meta Array in WP-REST API

I have been trying to pass a meta array to a post via front-end using WP-REST API but to no avail.
functions.php:
//Add custom field to REST API
function filter_post_json( $data, $post, $context ) {
$social_media = get_post_custom_values( 'social_media' );
$sm = [];
if($social_media):
foreach ( $social_media as $key => $value ) {
$sm[] = $value;
}
endif;
$data->data['social_media'] = $sm;
return $data;
}
add_filter( 'rest_prepare_custom-post-type', 'filter_post_json', 10, 3 );
add_action('rest_api_init', 'register_custom_meta');
function register_custom_meta() {
$post_custom_fields = array(
'social_media'
);
foreach ($post_custom_fields as $key) {
register_rest_field('custom-post-type', $key, array(
'schema' => null,
'get_callback' => 'get_meta_field',
'update_callback' => 'update_meta_field',
));
}
}
/**
* Handler for getting custom field data.
*
* #since 0.1.0
*
* #param array $object The object from the response
* #param string $field_name Name of field
* #param WP_REST_Request $request Current request
*
* #return mixed
*/
function get_meta_field( $object, $field_name, $request ) {
return get_post_meta( $object[ 'id' ], $field_name );
}
/**
* Handler for updating custom field data.
*
* #since 0.1.0
*
* #param mixed $value The value of the field
* #param object $object The object from the response
* #param string $field_name Name of field
*
* #return bool|int
*/
function update_meta_field( $value, $object, $field_name ) {
if ( ! $value || ! is_string( $value ) ) {
return;
}
return update_post_meta( $object->ID, $field_name, strip_tags( $value ) );
}
jQuery:
var sm1 = ['hi','hello'];
console.log(sm1);
var data = {
social_media: sm1
};
$.ajax({
method: "POST",
url: POST_SUBMITTER.root + 'wp/v2/custom',
data: data,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', POST_SUBMITTER.nonce );
},
success : function( response ) {
console.log( response );
alert( POST_SUBMITTER.success );
},
fail : function( response ) {
console.log( response );
alert( POST_SUBMITTER.failure );
}
This is the JSON output when I try to insert a post:
{
"id": 120,
"date": "2017-04-07T09:48:39",
"date_gmt": "2017-04-07T08:48:39",
"author": 1,
"featured_media": 0,
"menu_order": 0,
"template": "",
"format": "standard",
"social_media": [],
}
}
JSON output when I view a post (for brevity I have kept it short):
[
{
"id": 116,
"date": "2017-04-07T09:43:53",
"date_gmt": "2017-04-07T08:43:53",
"social_media": [
"facebook",
"instagram"
]
}]

How can I make register_rest_field return for some but not all endpoints?

I would like register_rest_field to return a certain field for a user only when a specific user is being requested (i.e. the request is /user/$user_id) -- not when /users or other endpoints are used.
One way I can think of to sort of do this would be to check the API request URL in the register_rest_field function and conditionally change the return value depending on the endpoint, but I don't know how to access that URL.
What would be the best way to do this?
You can use $request->get_url_params(); to check if request has $user_id or not.
Ref:
https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#arguments
<?php
add_filter( 'rest_prepare_user', 'mo_user_json', 10, 3);
function mo_user_json( $data, $user, $request ) {
$response_data = $data->get_data();
// for remove fields
unset($response_data['avatar_urls']);
unset($response_data['url']);
unset($response_data['description']);
// array user meta
$usermetas = [];
$metas = [
'field1',
'field2',
'field3',
'field4',
'field5',
'field6',
];
foreach ($metas as $meta) {
if(!empty(get_user_meta( $user->ID, $meta))){
$info = get_user_meta( $user->ID, $meta);
$usermetas[$meta] = $info[0];
}
}
// format json
$nodes = [
'field1' => $usermetas['field1']
'field2' => $usermetas['field2']
'field3' => $usermetas['field3'],
'field4' => [
'field4' => $usermetas['field4']
'field5' => $usermetas['field5']
'field6' => $usermetas['field6']
]
];
foreach ($nodes as $key => $node) {
$response_data['meta'][$key] = $node;
}
// add fields formated in json
$data->set_data( $response_data );
return $data;
}

Can't get username using current_user with WP-API inside functions.php

I can't get WP-API to show the current logged-in username for some reason it just shows an id : 0 and some other data.
functions.php
add_action( 'plugins_loaded', 'get_user_info' );
function get_user_info(){
global $current_user;
get_currentuserinfo();
return $current_user;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'cala', '/get', array(
'methods' => 'GET',
'callback' => 'get_user_info',
) );
} );
JSON
{
"data": {
},
"ID": 0,
"caps": [
],
"cap_key": null,
"roles": [
],
"allcaps": [
],
"filter": null
}
I am not sure if this is the best way either. Please help thanks.
Id "0" means the current user is logged out (visitor). Check you session status when you are firing the request.
Try wp_get_current_user() or get_current_user_id() maybe it will work better for you.

Resources