I can't access wp url parameter - wordpress

I'm trying to add an url parameter to a custom wp rest api endpoint, but when I access the endpoint using this url: mysite.com/wp-json/booking/pris?name=carl, I get this error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Here is my code:
add_action( 'rest_api_init', 'my_register_route_for_price' );
function my_register_route_for_price() {
global $wp;
$wp->add_query_var( 'name' );
register_rest_route( 'booking', 'pris', array(
'methods' => 'GET',
'callback' => 'get_price_callback',
)
);
}
function get_price_callback() {
$param = $request->get_url_params( 'name' );
return rest_ensure_response($param);
}

That's a WordPress security feature.
Undefined WordPress query variable outside the scope of the WP_Query class need to be defined first.
WP::add_query_var( string $qv )
Adds a query variable to the list of public query variables.
Use Case Scenario
<?php
add_action( 'init','wp67408336' );
function wp67408336() {
global $wp;
$wp->add_query_var( 'name' );
};
In any case
<?php
$name = htmlspecialchars( $_GET["name"] );

Related

Woocommerce Rest APi get custom meta field

I'm trying to pull a products custom meta and custom taxonomy value from woocommerce using the rest api. But no matter what I try a can't seem to get it to work. Not sure what I'm missing.
Example, my products have a custom meta value "product_location". The post meta value exists and works because I can use this to pull the value into the woocommerce product page:
get_post_meta($product->get_id(), 'product_location', true );
In my functions.php file I've added:
add_action( 'rest_api_init', 'handle_location' );
function handle_location() {
register_rest_field( 'post', 'product_location', array(
'get_callback' => array( $this, 'get_the_product_location' ),
'schema' => null
));
}
function get_the_product_location( $post, $field_name, $request ) {
return get_post_meta( $post[ 'id' ], $field_name, true );
}
However, when I make a call say https://*******.com/wc-api/v2/products/302341/ the meta data isn't included. So basically how can I include the additional meta data? I plan on trying this for a custom taxonomy as well. Any help is appreciated - Thanks
Try changing your bottom function to
function get_the_product_location( $post, $field_name, $request ) {
return get_post_meta( $post[ 'id' ], 'product_location', $meta_value );
}

Wordpress REST response shows taxonomy categories only with ID's

I'm using WP as a headless CMS with ACF en ACF-2-REST plugins. I've added categories to a post-type and when I make a GET call, it shows me all the information of a particular post including the categories, but only the ID's. If I want to match it, I have to do another call to Categories to get the information of that categories (name, parent etc).
How can I show that information instead of just the ID in a post call?
How the JSON looks now at the /activities call:
{
"id":111,
"date":"2020-01-18T15:39:27",
"date_gmt":"2020-01-18T15:39:27",
"guid":{"rendered":"https:\/\/url.be\/?post_type=activities&p=111"},
"modified":"2020-01-18T15:39:27",
"modified_gmt":"2020-01-18T15:39:27",
"slug":"walking-on-wood",
"status":"publish",
"type":"activities",
"link":"https:\/\/url.be\/activities\/walking-on-wood\/",
"title":{"rendered":"Walking on wood"},
"template":"",
"categories":[14,25,13,2,18,21,6,24],
"acf":{...}
}
What I want to show in the "categories" instead of just the numbers (from the categories call)
{
"id":3,
"count":1,
"description":"",
"link":"https:\/\/url.be\/category\/duration\/lower-than-30-min\/",
"name":"< 30 min.",
"slug":"lower-than-30-min",
"taxonomy":"category",
"parent":2,"meta":[],
"acf":[],
"_links":{"self":[{"href":"https:\/\/url.be\/wp-json\/wp\/v2\/categories\/3"}],
"collection":[{"href":"https:\/\/url.be\/wp-json\/wp\/v2\/categories"}],
"about":[{"href":"https:\/\/url.be\/wp-json\/wp\/v2\/taxonomies\/category"}],
"up":[{"embeddable":true,"href":"https:\/\/url.be\/wp-json\/wp\/v2\/categories\/2"}],
"wp:post_type":[{"href":"https:\/\/url.be\/wp-json\/wp\/v2\/posts?categories=3"},{"href":"https:\/\/url.be\/wp-json\/wp\/v2\/activities?categories=3"}],
"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}
}
Can't find any solution on the internet how I could manipulate the structure of that JSON with a custom function, would appreciate it a lot if someone point me to the right direction. Thanks!
As discussed in the comments section, a solution to this question is to use a custom endpoint method for the WP REST API and perform extra queries in there to get the data you need. This way, you can do all the data manipulation to get the perfect response, resulting in one REST call.
As taken from the official developer docs
Define an endpoint method and add some extra data
<?php
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func', //note that this is the method it will fire
'args' => array(
'id' => array(
'validate_callback' => function($param, $request, $key) {
return is_numeric( $param );
}
),
),
) );
/**
* Grab latest post by an author along with its category!
*
* #param array $data Options for the function.
* #return array Post,
*/
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if(!empty($posts)) {
//Example of appending extra data
foreach($posts as $post) {
$category = wp_get_post_terms($post->ID, 'category');
$post['category'] = $category;
}
return $posts;
} else {
return new WP_Error( 'no_author', 'Invalid author', array( 'status' => 404 ) );
}
}

Wordpress REST API reading post meta but not updating

I am trying to create a PowerApp in which I want to integrate the post meta fields. I inserted this code in the functions.php file. But I can read and write the data for default WordPress fields, but I am not able to update the post custom fields.
add_action( 'rest_api_init', 'create_api_posts_meta_field' );
function create_api_posts_meta_field() {
// register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
register_rest_field( 'post', 'post-meta-fields', array(
'get_callback' => 'get_post_meta_for_api',
'update_callback' => 'get_post_meta_update_for_api',
'schema' => null,
)
);
}
function get_post_meta_for_api( $object ) {
//get the id of the post object array
$post_id = $object['id'];
//return the post meta
return get_post_meta( $post_id );
}
function get_post_meta_update_for_api( $value, $object, $field_name ) {
return update_post_meta( $object[ 'id' ], $field_name, $value );
}

update_callback not calling proper function when sending post

So, here's my code so far:
add_action( 'rest_api_init', 'rest_api_user_meta_fields' );
function rest_api_user_meta_fields() {
// register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
register_rest_field( 'user', 'grad', array(
'get_callback' => 'get_user_acf_fields',
'update_callback' => 'update_user_acf_fields',
'schema' => null,
)
);
}
function get_user_acf_fields( $object ) {
//get the id of the post object array
$grad = get_field('grad', 'user_32');
error_log($object);
return $grad;
}
function update_user_acf_fields( $value, $object, $field_name ) {
error_log($value);
error_log($field_name);
error_log($object);
}
Now, I expect to have get_user_acf_fields function to be executed when I send GET request to /users/ endpoint, and update_user_acf_fields to be run when I send POST request to said endpoint. In both cases it executes former, get_user_acf_fields, function. What am I doing wrong here?
Maybe you didn't include the proper nonce?
For developers making manual Ajax requests, the nonce will need to be
passed with each request. The API uses nonces with the action set to
wp_rest. These can then be passed to the API via the _wpnonce data
parameter (either POST data or in the query for GET requests), or via
the X-WP-Nonce header. If no nonce is provided the API will set the
current user to 0, turning the request into an unauthenticated
request, even if you’re logged into WordPress.
— Read more on https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
Here's your code that I modified and tested working on WordPress 4.9.5 with Advanced Custom Fields 4.4.12.
add_action( 'rest_api_init', 'rest_api_user_meta_fields' );
function rest_api_user_meta_fields() {
// register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
register_rest_field( 'user', 'grad', array(
'get_callback' => 'get_user_acf_fields',
'update_callback' => 'update_user_acf_fields',
'schema' => [
'description' => 'User grad blah',
'type' => 'string',
],
)
);
}
// $user_arr is an `array` of the user data; e.g. `id`, `username`, and `name`.
// $field_name is the name of the ACF custom field; i.e. in this case, it's `grad`.
function get_user_acf_fields( $user_arr, $field_name ) {
// Get the value of the 'grad' custom field.
$grad = get_field($field_name, 'user_' . $user_arr['id']);
error_log(var_export( $user_arr, true ));
error_log($field_name);
//return $grad;
return $field_name . ';' . $grad . ';' . $user_arr['id'];
}
// $field_value is the value of the ACF custom field; i.e. in this case, it's `grad`.
// $user_obj is an `object` of the user data; e.g. `id`, `username`, and `name`.
function update_user_acf_fields( $field_value, $user_obj, $field_name ) {
// Get the value of the 'grad' custom field.
$grad = get_field($field_name, 'user_' . $user_obj->ID);
if ( $grad !== $field_value ) {
update_field( $field_name, $field_value, 'user_' . $user_obj->ID );
}
error_log($field_value);
error_log($field_name);
error_log(var_export( $user_obj, true ));
return true;
}
And here's the HTML and JS/AJAX I used for testing the PHP code above.
$_GET, $_POST and UPDATE are different things to the rest API. Since update isn't necessarily a construct of the language it just means that when a request usually a $_POST comes in with a specific "Update" header that it should call your update function.

add_action() but function is never called

I've created a custom wordpress plugin in which I'm defining a custom post type and at one point I'm calling add_action to set custom column in the admin.
The 'manage_[custompostname]_posts_columns' is working great, but the 'manage_[custompostname]_posts_custom_column' do not.
add_filter('manage_bbc_cp_game_posts_columns', bbc_cp_game_table_head');
function bbc_cp_game_table_head( $defaults ) {
$columns = array(
'team_id' => 'Equipe',
'opponent_id' => 'Adversaire',
'gamedatetime' => 'Date / heure',
'score' => 'Score'
);
return $columns;
}
add_action( 'manage_bbc_cp_game_posts_custom_column', 'bbc_cp_game_table_content', 10, 2 );
function bbc_cp_game_table_content( $column, $post_id ) { die('it should work'); }
The second add_action returns true, but the function is never called.
I'd really appreciate if any of you had an idea of what could be the issue, or how to debug it.
Thanks,

Resources