Hot answers tagged

81

You can get it without plugins by adding _embedas param to your query /?rest_route=/wp/v2/posts&_embed /wp-json/wp/v2/posts?_embed


66

Since I don't like it myself when the top answer is "Install plugin X", here is how I solved it: Menus are currently not available in the WP Rest. So what you need to do is register your own custom endpoint and then just call that route from your application that needs it. So you would include something like this (in your functions.php, plugin, wherever): ...


31

There is an elegant way to handle this! Pass the JSON encoded string through wp_slash(). That function will escape the leading slash of each encoded unicode character, which will prevent update_metadata() from stripping them.


26

Ah I just had this problem myself! And while _embed is great, in my experience it is very slow, and the point of JSON is to be fast :D I have the following code in a plugin (used for adding custom post types), but I imagine you could put it in your theme's function.php file. php add_action( 'rest_api_init', 'add_thumbnail_to_JSON' ); function ...


25

Try setting the data_format parameter in your request like so: $data = wp_remote_post($url, array( 'headers' => array('Content-Type' => 'application/json; charset=utf-8'), 'body' => json_encode($array_with_parameters), 'method' => 'POST', 'data_format' => 'body', )); It looks like the format may be defaulting ...


24

wp_send_json() handles all parts of returning content in an AJAX call. First off, it sets the content type of the returned content to application/json with the proper charset. Secondly, it automatically calls wp_die() after sending the JSON result, which is necessary in an AJAX call in WordPress. You could consider using wp_send_json_success() for ...


15

TL;DR Yes, WordPress can certainly act as a backend for a mobile app. Yes, a page can act as a rest endpoint / interface. No, a theme template is not the right territory for the logic. Write your own plugin. Pointers I find it hard to believe that no one else has done this. I, for one, have. More than once. And I'm near certain I'm not alone. "No one ...


14

I would NOT use the better rest API plugin. It did add featured images to the rest api but it also broke it. This is the simplest solution I was able to find that actually worked. Add the following code to your functions.php: <?php function post_featured_image_json( $data, $post, $context ) { $featured_image_id = $data->data['featured_media']; // ...


12

I don't think using React.js without Node.js (or at least V8 or rhino etc) counts as isomorphic, as isomorphic means that you are building JavaScript to run in the browser AND on the server. Specifically, using WordPress certainly means you aren't doing isomorphic javascript (its PHP software). What you could do is use WordPress as a REST API server, and ...


11

If you need to send a JSON response, then there's a set of functions for that. In case you need that for an AJAX callback: wp_remote_retrieve_response_message() wp_remote_retrieve_response_code() wp_send_json_success() wp_send_json_error() wp_send_json() Would finally be something like that: $request = wp_remote_get( 'http://example.com' ); $response = ...


11

it seems the latter only accepts x-www-form-urlencoded That's not completely true. WordPress admin-ajax.php takes the action from $_REQUEST['action'] and $_REQUEST is equal to: array_merge($_POST, $_GET); But what many people don't realize is that $_GET in PHP is not the data was sent to page using HTTP GET method, in fact, you can use whatever HTTP ...


11

Based on the code provided it looks like you are misunderstanding how wp_localize_script works. The signature of the function looks like this: wp_localize_script( $handle, $name, $data ); Where $handle is the name of a JavaScript file you have registered or enqueued before calling wp_localize_script. Take a look at the example in the codex (I've added line ...


9

Sorry for answering my own question but it may help some other devs too. I created this additional filter 'json_query_var-meta_query'that returns the necessary arguments. function adjustQrry($data){ $args = array(); $args['relation'] = 'AND'; foreach ($data as $key=>$value) { if ( 'relation' === $key ) { $args['relation']...


9

Just add the _embed query argument to your URL asking for the posts, and every post object, will include the _embedded.[wp:featuredmedia] object, which includes all the images, just like the /media/$id resource. If you want an specific size, just access it by its property name, i.e.: _embedded[wp:featuredmedia][0].media_details.sizes.full.source_url or for ...


8

BODA82's answer helped, but eventually I realized that I should have replaced responseText with responseJSON method in my JavaScript code. In the example below I was storing the Ajax response results in a variable. I didn't know there was a specific method to get the response in JSON. In a such way the object/array with get_posts() results is returned ...


8

Use wp_remote_get() in conjunction with wp_remote_retrieve_body() Example <?php $request = wp_remote_get('http://example.com'); $response = wp_remote_retrieve_body( $request ); echo $response; ?> Check the documentation for possible arguements


8

This is the approach to add a rewrite rule for swapping out the template that WP wants to render (usually the 404 template) with something else. In your case you're just wanting to die with some JSON data so there are a bunch of different ways to do this. This is the "by the book" approach to adding a rewrite rule instead of a hack to check the URL on your ...


8

I will give you a small answer to your update, doing this with the WP API. The API have the possibilities to use the WP_Query like also in core, but about the get parameters in the url. A URL to pull content from Post Status would look like this: http://example.com/wp-json/posts To pull content with WP_Query parameters you’re used to, you could do it like ...


8

If possible, only the examples shown in internet is: function qod_remove_extra_data($data, $post, $context) { // We only want to modify the 'view' context, for reading posts if ($context !== 'view' || is_wp_error($data)) { return $data; } // Here, we unset any data we do not want to see on the front end: unset($data['author']);...


8

I got it. Turns out the tutorial I was looking at was old and I was using the wrong WP function. I was using register_api_field but the correct one to use is register_rest_field. It goes like this... function facebook_add_user_data() { register_rest_field( 'user', 'facebook', array( 'get_callback' => 'rest_get_user_field', '...


8

The filter param was removed in WP4.7, you should be able to access tags via their ID. For example to get the tag with the ID of 7 you could use: http://YOUSIITE.DEV/wp-json/wp/v2/posts?tags=7 If you would like to add filters back in the WP-API team released their own Filter plugin, I'd recommend that you check that out: https://github.com/WP-API/rest-...


8

You can use wp_localize_script to pass an object with the url to load before the file. and then in the file you can use it like testpage_obj.json_data wp_register_script('testpage', get_stylesheet_directory_uri() . '/js/testscript.js', array('jquery'), '', true); wp_localize_script( 'testpage', 'testpage_obj', array( 'json_data' => ...


7

@Liren answer works well. However few beginners may not able to adjust the route. Here is the code that works well with WordPress Rest API v2 with minimum modification. Replace your menu name only in wp_get_nav_menu_items() function. If menu name and slug does not work (Return false), use Menu ID (visible in Dashboard while editing that Menu). function ...


7

If you want the D.I.Y. route... The post type in this example is set to 'post' but you can see where to change it. Here is a working example to pull the data ( first page in this example ), parse the response, create a class for the clean(er) data, generate posts from that data then update the post meta for specific attributes. You'll want to adjust what ...


7

You can get the name of the image with this path: array_name._embedded['wp:featuredmedia']['0'].source_url


7

Wordfence blocks the User endpoint from the public. In settings there is a checkbox you can unselect to make it visible in the WP Rest API again.


7

The REST API included in WordPress doesn't actually have authentication built into it. If you do normal authentication in WordPress by logging in, then your browser will receive a set of cookies. If you send those cookies along with your request, then that will authenticate you to perform the actions in question. If you need to add authentication for an ...


7

I ended up extending the API like suggested in the comments to my question, although I was hoping there was a default route that fetched all posts of all post types. Apparently, there isn't. So here's my solution: add_action( 'rest_api_init', 'custom_api_get_all_posts' ); function custom_api_get_all_posts() { register_rest_route( 'custom/v1', '/...


7

The API responses are designed to only return the IDs. You can then fetch the full information for each term. Of course it would not be very performant to make dozens of requests. So instead, the REST API has the concept of embedding resources. If you make your request, but include _embed=1 in your URL, WordPress will make those requests for each term for ...


6

You can actually find extensive documentation on wordpress.org. But let's have a look at this particular example: https://demo.wp-api.org/wp-json/wp/v2/posts?per_page=5&tags=3 The 5 in there is the number of posts you want returned. The 3 is the id of the tag you want to limit the posts too. If you want to limit to a category use categories instead. ...


Only top voted, non community-wiki answers of a minimum length are eligible