Now that the WP-API is in core, here are some useful tips for you.
Filtering Posts
Filtering posts was a bit confusing for me at first, because the documentation seems to suggest you would visit an endpoint like /posts/category/40 to get posts from a certain category.
Instead, you are supposed to use arguments in your request. For example, to show a certain category, you would make a GET request to this url:
https://yoursite.com/wp-json/wp/v2/posts?categories=40
The ’40’ at the end is the category term ID. You can do the same for tags by changing the parameter to ?tags=XX.
There are other parameters available, such as author, orderby, exclude, and more. For a full list, please see the “Arguments” section here.
You can string parameters like this:
https://yoursite.com/wp-json/wp/v2/posts?categories=40&author=1&exclude=214
?filter
There is no longer an option for ?filter, which was really handy for custom taxonomies. I would guess this will be added back at some point, but for now you can use this plugin.
That allows you to use WP Query arguments in your request, for example:
https://example.com/wp-json/wp/v2/posts?filter[name]=the-slug
Custom Post Type Support
I’ve covered this before, but the WP-API won’t show CPTs by default. To add support for an existing CPT:
add_action( 'init', 'my_custom_post_type_rest_support', 25 );
function my_custom_post_type_rest_support() {
global $wp_post_types;
//be sure to set this to the name of your post type!
$post_type_name = 'product';
if( isset( $wp_post_types[ $post_type_name ] ) ) {
$wp_post_types[$post_type_name]->show_in_rest = true;
}
}
In the example above, your products would then show at the url wp-json/wp/v2/product.
You can also set ‘show_in_rest’ to true when registering the post type instead. See this post for more details.
Custom Endpoints
The documentation covers this fairly well, but if you want to add your own endpoint it looks like this:
add_action( 'rest_api_init', function () {
register_rest_route( 'sb/v1', '/author/(?P\id+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );
/**
* Grab latest post title by an author!
*
* @param array $data Options for the function.
* @return string|null Post title for the latest,? * or null if none.
*/
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return null;
}
return $posts[0]->post_title;
}
You can then send a GET request to http://example.com/wp-json/sb/v1/author/1 and get all the posts by the author with an ID of 1.
Post Meta
Post meta doesn’t show up by default, you have to add it. Here’s an example for adding the WooCommerce price:
add_action( 'rest_api_init', 'sb_register_post_meta' );
function sb_register_post_meta() {
register_rest_field( 'product', // any post type registered with API
'_price', // this needs to match meta key
array(
'get_callback' => 'sb_get_meta',
'update_callback' => null,
'schema' => null,
)
);
}
function sb_get_meta( $object, $field_name, $request ) {
return get_post_meta( $object[ 'id' ], $field_name, true );
}
CORS Errors
If you are getting CORS errors from your API requests, you can try adding this code to your site:
header("Access-Control-Allow-Origin: *");
You can add it inside an action such as send_headers, but sometimes the only way it works is to add it at the top of a plugin file.
CORS is there for safety, so adding this may be unsafe. Please consult a security professional before using this code on your site.
That’s all I’ve got for now, leave your tips in the comments.
Comments
3 responses to “Some WP-API Tips for WordPress 4.7+”
Sorry, you can delete my last comment. I got that the call gives me all variations back.
Ok let me specify my case. I am currently working on a food delivery site for a client of mine. Pizzas come in different sizes of course. So i got size S, M, L, XL set up as product variations.
But now it drives me totally nuts. I implemented the _product_attributes field according to your tutorial. And it returns the following:
“_product_attributes”: {
“size”: {
“name”: “Size”,
“value”: “Single | Jumbo | Family | Party”,
“position”: “0”,
“is_visible”: 1,
“is_variation”: 1,
“is_taxonomy”: 0
}
},
meaning it tells me ALL values. But not which one it is. I absolutely underestimated WooCommerce for it’s ease of customizability and I’m so waaaaay overdue on this project 😀 .
Starting to cry right now I guess … lol … please give me your opinion.
Thanks a lot
Andy
Hi Andy, I don’t know about that one sorry. WooCommerce has it’s own API, you may want to use that instead of the WP-API. https://docs.woocommerce.com/document/woocommerce-rest-api/
Hi,
i have a add customer filed in postmeta (product) with woocommerce_product_data_panels.
I would to add product with API and post same value in this new flied.
i have copier your code in my function of the theme i cant see my new filed in api