WordPress JSON output

If you are using PHP 5.2+ you’re best bet is to just make a PHP array or object and use json_encode(). UPDATED: $cats = get_categories(); $output = array(‘categories’ => array()); foreach ($cats as $cat) { $cat_output = array( ‘cat_id’ => $cat->term_id, ‘cat_name’ => $cat->name, ‘posts’ => array(), ); // should be able to use -1 … Read more

What is the best way to get directory path for wp-config.php?

I came up with this solution. This function checks in each directory level starting from the directory of the current file for the file wp-config.php. <?php function find_wp_config_path() { $dir = dirname(__FILE__); do { if( file_exists($dir.”/wp-config.php”) ) { return $dir; } } while( $dir = realpath(“$dir/..”) ); return null; } ?> To actually include the … Read more

WP REST API only returning partial list of users

To anyone who might still be hitting this problem, here’s a checklist: Make sure you are authenticated AND your user has the list_users capability. Example: When adding a custom role, I make sure to add the list_users capability. The user should also be logged in (what authenticated means) when making the request. By default, only … Read more

Create API for single sign-on with 3rd party site

Cross-site Scripting Issues You cannot transfer WP auth cookies between domains. You also don’t want to store plaintext passwords for logging into another WP installation programmatically. So, you’ll have to have users log into WordPress, and then access their login status via an API endpoint from the third-party site. This lets WordPress handle all the … Read more

WordPress Rest API custom endpoint optional param

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 make it more complex