Hot answers tagged

76

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


27

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] => )


27

The API you offer in a plugin or a theme depends on the logic of that specific code. There is probably no guide that applies to all situations. I am a contributor for multiple plugins with APIs, and what I have learned so far is: Do not offer an API until you really know how people use your code. Release the first two or three versions without any API. No ...


24

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 ...


21

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 )...


18

I think the best option is an endpoint. You get all the data as a simple string, so you can decide how it will be parsed, and you don’t have to worry about collisions with other rewrite rules. One thing I learned about endpoints: keep the main work as abstract as possible, fix the glitches in WordPress’ API in a data agnostic way. I would separate the ...


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 have a few issues with the accepted answer - that doesn't make it wrong, but I'll post my own code below which I feel might have a better result for some people since I had the same question but wanted to do the same thing with less code. First, the above code creates "URL" type navigation items, which is fine for some people but I want to link to PAGES, ...


13

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

If you look at the source for the add_action() core function, it's just a wrapper for add_filter() function... And if you look at the do_action() core function, it's very similar to the apply_filters() core function, with one very key difference: it does not return a value. So what does this mean? actions are like filters, except an action does not return ...


11

I know it's been a while, but if anyone else stumbles on this, I found a WordPress hook specifically for modifying HTTP headers. The hook is wp_headers and it's called in the wp class. The first argument passed is an array of headers with the header name as the key. The second argument is a reference to the wp class object.


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 = $...


10

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

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' ] }, });


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

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 ...


8

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


8

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>


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 ...


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