Hot answers tagged

80

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


30

The most comprehensive method is get_current_screen added in WordPress 3.1 $screen = get_current_screen(); returns WP_Screen Object ( [action] => [base] => post [id] => post [is_network] => [is_user] => [parent_base] => edit [parent_file] => edit.php [post_type] => post [taxonomy] => )


26

You should put the named parameters of the route regex into an optional capturing group: register_rest_route( 'api', '/animals(?:/(?P<id>\d+))?', [ 'methods' => WP_REST_Server::READABLE, 'callback' => 'get_animals', 'args' => [ 'id' ], ] ); The second parameter is simply a regex, thus you can use normal regex logic to ...


23

The problem of building a tree from a flat array has been solved here with this, slightly modified, recursive solution: /** * Modification of "Build a tree from a flat array in PHP" * * Authors: @DSkinner, @ImmortalFirefly and @SteveEdson * * @link https://stackoverflow.com/a/28429487/2078474 */ function buildTree( array &$elements, $parentId = 0 )...


15

Here is the code I've used, based on the original question and on Dominic P's answer... /* * Modify HTTP header */ function add_header_xua($headers) { // var_dump($headers); #=> if you want to see the current headers... if (!is_admin()) { $headers['X-UA-Compatible'] = 'IE=edge,chrome=1'; } return $headers; } ...


15

An alternative to get_plugin_data() is get_file_data() which is available without the overhead of loading additional files. Simply add this to your main plugin file: $plugin_data = get_file_data(__FILE__, array('Version' => 'Version'), false); $plugin_version = $plugin_data['Version']; Under the hood get_file_data does some cleaver scanning to be ...


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

It's been a while since this question was asked, but on the off chance that you are still looking for a solution: items_frame = wp.media.frames.items = wp.media({ title: 'Add to Gallery', button: { text: 'Select' }, library: { type: [ 'video', 'image' ] }, });


11

If your extra data directly references a post meta you don't have to do anything, because WP_Post implements the »magic« methods __isset() and __get() which directly asks for post meta keys (except for the following four keys: page_template, post_category, tags_input and ancestors). Here's a quick example that shows the behavior: <?php $post_id = 42; $...


10

You can call the REST API methods to prepare your output in the same way that the plugin does by default, this will also allow any plugins to tie into the output as you have used the ACF plugin as seen in your example output. The WP_REST_Posts_Controller class has the following in its get posts method $posts_query = new WP_Query(); $query_result = $...


9

Update: Made a blog post to explain this better :) I was able to do this by WP's authenticate filter inside a new plugin; most of which is guided by this tutorial by Ben Lobaugh. Major points on the plugin: Make an API call function using cURL (you can get guide codes from Postman upon testing if you don't know already). Add filter checking if the response ...


9

get_userdata() function is an alias of get_user_by('ID') function. Use this code: $username = 'your user name'; $user = get_user_by('login', $username); It will return WP_User object on success, or false on failure. See Codex. REST API: http://example.com/wp-json/wp/v2/users/<id>


8

I tried for a bit and could not get this to work perfectly, but it's close, it's hard to extend with the <form> for the popup styles being hardcoded, thought possible with more work. To get started you can: Enqueue the link popup javascript and styles, the main .js file is wp-includes/wplink.js. Depending on where you loading this you might need to ...


8

You can Disable HTTP Calls by adding this in your wp-config.php define( 'WP_HTTP_BLOCK_EXTERNAL', TRUE ); This will disable/block all external HTTP requests and will make website alot faster. And then you can whitelist domains that you don't want to block. define( 'WP_ACCESSIBLE_HOSTS', 'example.com, domain.com' );


8

Yes, WordPress has modal dialog and it is called as Thickbox, but I am not sure how flexible it is to implement what you want to. Here is the code - <?php add_thickbox(); ?> <div id="my-content-id" style="display:none;"> <p> This is my hidden content! It will appear in ThickBox when the link is clicked. </p> </...


8

See if your url is correct. Example: website.com/wp-json/wp/v2/posts/?categories=3&per_page=‌​50


7

Ok - here is a method - thanks to @Rarst for pointing me in the right direction. Include the require file if the plugins_api function is not found: if ( ! function_exists( 'plugins_api' ) ) { require_once( ABSPATH . 'wp-admin/includes/plugin-install.php' ); } Then, prepare a query to pass to plugins_api(): // set the arguments to get latest info ...


7

This question is going to get some opinion based answers, but well, I'll give it a try. There are a couple of reasons why someone might've told you that, it would be great to know the context also. Upto version 3.4 or 3.5, that function only worked when the parameter was a var, that might be one of the reasons why someone told you that. I, myself, don't ...


7

For starters let's dive into what is 5 really. It is the post's ID. But what is ID in turn? It is value in the MySQL table row which identifies the specific post record. Issues with using IDs So first there are some conceptual problems with it. It's not content. It's not something user creates, manipulates, or (most of the time) aware of. WP is (by design) ...


7

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


7

I'd recommend writing a simple plugin. Read through the Plugin Development Handbook, but it's pretty easy. The only thing necessary for a plugin is the header with the Plugin Name. In the plugin, create a function that gets and stores in a WordPress transient the result of an API request. <?php /** * Plugin Name: WordPress StackExchange Question ...


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', '/...


6

In simple word's. Actions are those PHP functions which execute the output. Filters are those PHP functions which return the output. Updated: We can extend any plugin which use the actions and filters without modifying there code. By adding filters and actions in our own theme or plugin. How to use? Action: Check below simple examples in your ...


6

TL;DR There is no JavaScript API in the WordPress core and no one is planned, but actually, there is no need of it. Backend First of all let's say that, regarding the backend, some useful information can be fetched from already present JavaScript global variables (WordPress loves all global flavors). E.g. ajaxurl for the admin-ajax.php url to be used in ...


6

Both approaches are not mutually exclusive. As @gmazzap said, don’t create a callback hell. But you can provide an initial hook, so other developers don’t have to rely on the rather slow function_exists() checks. Example In your plugin, provide a hook that other developers can use to call your classes and functions safely. add_action( 'wp_loaded', [new ...


6

I'm using the REST API to pull data about one multisite installation and feed it to sites in another multisite installation. Here's some of the code in use: class WPSE205354_Demo { function __construct() { add_filter( 'json_endpoints', array( $this, 'register_routes' ) ); } /** * Register the additional API routes * @param ...


6

GET requests, like listing posts, doesn't need authentication at least you need to get private posts. Your problem is that you are using a route/endpoint that doesn't exist. In WordPress 4.4, WP REST API infrastructure was merged, endpoints didn't; they will be merged in WordPress 4.5 (as WordPress 4.6 it seems endpoints are still don't included in core). ...


6

I figured something out based on what I found at this post. Basically I need a plugin that listens for when the REST response is about to go out. The plugin code would be similar to the following: function ag_filter_post_json($response, $post, $context) { $tags = wp_get_post_tags($post->ID); $response->data['tag_names'] = []; foreach ($...


6

Yes, you open your site to being requested via AJAX to any other script in the whole web. It would be better if you limit the origin to one specific remote domain from which you are consuming the API, like this example: header("Access-Control-Allow-Origin: http://mozilla.com"); However as the mozilla documentation states, a client can fork the origin, ...


6

Well, I figured it out. Though my solution is probably far from elegant (I'm not making concessions for timeouts or usability/accessibility). My problem was mostly overzealous configuration, copy and paste errors, and needing to apply async/await keywords. Attributes look like this: attributes: { url: { source: 'attribute', type: '...


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