POST method in WordPress REST API - wordpress

I want to use POST methon from REST API tu update a user profile from a backend website to FrontEnd WordPress. The next code is suppose to update the name, description and the slug.
if (isset($_POST['update_frontend'])) {
$url = $setting['front_end_host_wp'].'users/'.$item_id.'/';
$data1 = array(
'description' => $data['content'],
'name' => $data['nume'],
'slug' => $data['slug'],
'parent' => 0,
'meta' => array()
);
$result = $df->runGuzzle('POST', $url, $data1);
printpre($result);
}
I want to update the user_status(Approved, Pending or Denied) and other info like, name, email etc. But the code above is not working.

Related

Resolved: Wordpress API Post request not updating

I'm tring to write a WordPress post request (API) and although it reports a success message, the data is not updated. I temporarily created two extra columns in the WordPress user table (yes, not best practice). But the data is not saved. The jwt-auth plugin is used.
Current rest route:
register_rest_route( 'jwt-auth/v1', 'base_coords_post', array(
'methods' => 'POST',
'callback' => 'base_coords_post',
));
And the callback
function base_coords_post() {
global $wpdb;
$userId = get_current_user_id();
$data = array(
'lat' => $_POST['lat'],
'lng' => $_POST['lng']
);
$data_where = array(
'ID' => $userId
);
$wpdb->update($wpdb->users , $data, $data_where);
}
How is it that the columns are not being updated? I checked the post values, they exist, the userID also exists.
EDIT
The fix was i tried to add varchar longer than the database field can hold. Changing the DB fixed the issue.

How to filter custom fields for custom post type in wordpress rest api?

I use wordpress standard with the plugins "Advanced custom fields" and "custom_post_type ui". I created a post_type called deals and added some custom fields with it.
What I need to do now, is filter the results when accessing the rest api like this:
http://localhost:8000/wp-json/wp/v2/deals
Actually I only need the acf part of it. I dont care about the rest.
[{"id":29,"date":"2019-04-12T12:34:14","date_gmt":"2019-04-
12T12:34:14","guid":{"rendered":"http:\/\/localhost:8000\/?
post_type=deals&p=29"},"modified":"2019-04-
12T12:34:14","modified_gmt":"2019-04-12T12:34:14",
"slug":"test-title","status":"publish","type":"deals",
"link":"http:\/\/localhost:8000\/deal s\/test- title\/","template":"",
"meta":[],"tax-deals":[],"acf":{"title":"Title for Deals
Post","description":"","image":false,"date_start":"01.01.1970",
"date_end":"01.01.1970","category":"Kleidung"},"_links":{"self":
[{"href":"http:\/\/localhost:8000\/wp-json\/wp\/v2\/deals\/29"}],
"collection":[{"href":"http:\/\/localhost:8000\/wp-
json\/wp\/v2\/deals"}],"about":[{"href":"http:\/\/localhost:8000\/wp-
json\/wp\/v2\/types\/deals"}],"wp:attachment":
[{"href":"http:\/\/localhost:8000\/wp-json\/wp\/v2\/media?
parent=29"}],"wp:term":[{"taxonomy":"tax_deals","embeddable":true,
"href":"http:\/\/localhost:8000\/wp-json\/wp\/v2\/tax-deals?
post=29"}],"curies":
[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},
I have already tried using
http://localhost:8000/wp-json/wp/v2/deals?search=id
to get the id or something, but response is empty.
Also this didnt work:
http://localhost:8000/wp-json/wp/v2/deals?id=28
Again empty response.
To summarize: I need to filter my custom post type on my custom fields by the "acf" attribute shown in my response json. How does it work?
EDIT: I already installed "WP REST Filter" but still dont know how to do it.
I suggest you to create a new API where you can customize the output. Take advantage of wordpress function register_rest_route() using this you can create an API from CPT and ACF in one ajax url. And you do not need to install anything.
Check how I get my instructor CPT and mycheckbox ACF.
// your ajaxurl will be: http://localhost/yoursite/wp-json/custom/v2/instructor/
add_action( 'rest_api_init', function () {
register_rest_route( 'custom/v2', '/instructor', array(
'methods' => 'GET',
'callback' => 'instructor_json_query',
));
});
// the callback function
function instructor_json_query(){
// args to get the instructor
$args = array(
'post_type' => 'instructor',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'mycheckbox', // your acf key
'compare' => '=',
'value' => '1' // your acf value
)
)
);
$posts = get_posts($args);
// check if $post is empty
if ( empty( $posts ) ) {
return null;
}
// Store data inside $ins_data
$ins_data = array();
$i = 0;
foreach ( $posts as $post ) {
$ins_data[] = array( // you can ad anything here and as many as you want
'id' => $posts[$i]->ID,
'slug' => $posts[$i]->post_name,
'name' => $posts[$i]->post_title,
'imgurl' => get_the_post_thumbnail_url( $posts[$i]->ID, 'medium' ),
);
$i++;
}
// Returned Data
return $ins_data;
}
Then, you can use the link: http://localhost/yoursite/wp-json/custom/v2/instructor/ in your ajax url.

Update User Meta with spaces using REST API - WordPress

I'm trying to update the user meta with spaces registered on my website. I am using register_meta hook to register user meta. And for updating users using WordPress REST API I use wp_remote_post but the problem is when I tried to update a user meta with spaces it will add as array in response then it will add as new user meta.
For example the value of user meta is - community test
Sample Response:
[meta] => Array
(
[agent_community] => Array
(
[0] => community
[1] => test
)
)
Sample Code for registering user meta.
register_meta('user', 'agent_community', array(
"type" => "string",
"show_in_rest" => true
));
Update using wp_remote_post
$update_data = array('email'=> 'test#mail.com', 'meta[agent_community]' => 'community test');
$args = array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'username:password' ),
),
'body' => array_filter($update_data));
$update_url = 'https://test-url.com/wp-json/wp/v2/users/17';
$response = wp_remote_post( $update_url, $args);
Database:
Is there a way that can merge the array on user meta?
implode() might help you. And you can change spaces with HTML entities. Or use function like urledncode() / urlendecode() or something like this.

Woocommerce using JWT Authentication and using API for customers

I would want to use the Woocommerce REST API using JWT as the authentication and I would want to use the API for customers.
The point of the inquiry is that I am building a mobile e-commerce application on iOS and Android and would want to use my existing Woocommerce for this.
You can get your user inside a custom endpoint like this:
if (is_user_logged_in()) {
$user = wp_get_current_user();
if($user->exists()){
return rest_ensure_response($user);
}
}
return rest_ensure_response(array("data" => "no user logged in"));
the code above will return all data from the user related to the JWT token used for the request, so be careful if you don't want to send any sensitive data.
you can retrieve data from the user with the woocommerce Rest api, https://woocommerce.github.io/woocommerce-rest-api-docs/#retrieve-an-order, or with the plugin functions:
$query = new WC_Order_Query();
$query->set( 'customer', $user->data->user_email);
$orders = $query->get_orders();
$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => wc_get_order_types(),
'post_status' => array_keys( wc_get_order_statuses() ),
) );
hope it helps.

Custom Post Type & Author not associating, user post count is 0, api doesn't return author in post objects

When Users create custom post types, the author field does not seem to be passed back to WP posts functions.
As the title says, I'm creating a user account programatically, and having that user log-in and write a post of custom post_type = 'job'.
This all LOOKS good in the database - the user, and post are inserted. The post_author is indeed the same as the ID of the user who created it.
But, in the User Accounts panel, that user post count is 0, and the API data object omits the author. I've configured the API for the additional custom post type and the endpoint works to return all post data EXCEPT author.
I've tried creating a post from the CMS with these users as well, and likewise, even if I give them Administrator permissions, they have a 0 post count - the posts are attributed to their author ID. I've also tried to force and update using wp_update_post();
Here's the code to create the user, and then the post:
// Generate the password and create the user
$password = wp_generate_password( 12, false );
$user_id = wp_create_user( $email_address, $password, $email_address );
//login
wp_clear_auth_cookie();
wp_set_current_user ( $user_id );
wp_set_auth_cookie ( $user_id );
// Set the role
$user = new WP_User( $user_id );
$user->set_role( 'subscriber' );
//Ready data for linked post type creation
$new_post = array(
'post_content' => $email_address,
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_id,
'post_title' => $post_name,
'post_name' => $post_name,
'post_type' => $user_type
);
//Create the post
$account_link_post_id = wp_insert_post($new_post);
There was an associated post to this one that shed light on this answer. When registering the post type, I was not setting enough fields in the 'supports' array of the register_post_type. Adding author, whatdayaknow, gives me the datapoint I'm looking for.
register_post_type(self::POST_TYPE,
array(
'labels' => $labels,
'public' => true,
'has_archive' => true,
'description' => __(""),
'supports' => array(
'title', 'author'
),
)
)
NOTE: Post count in the User Accounts page is still 0 - but, the API is returning the data I want/need.

Resources