Extending WordPress REST API and WP-CLI

Summary: Learning about the Extending WordPress REST API using custom controller, WP-CLI packages and WP-CLI scaffold commands.

Extending WordPress REST API

WordPress provides a powerful REST API that allows us to interact with our WordPress site from external applications. Sometimes the default REST API endpoints don’t meet our requirements and we may need to create custom endpoints or extend existing ones. This is where custom controllers can be used.

Creating a Custom Controller

class Movie_Library_REST_Controller extends WP_REST_Controller {

    // Constructor
    public function __construct() {
        $this->namespace = 'movie-library/v1';
        $this->rest_base = 'movies';
    }

    // Register the routes
    public function register_routes() {
        register_rest_route($this->namespace, '/' . $this->rest_base, array(
            array(
                'methods' => WP_REST_Server::READABLE,
                'callback' => array($this, 'get_movies'),
                'permission_callback' => array($this, 'get_movies_permissions_check'),
            ),
            array(
                'methods' => WP_REST_Server::CREATABLE,
                'callback' => array($this, 'create_movie'),
                'permission_callback' => array($this, 'create_movie_permissions_check'),
                'args' => $this->get_endpoint_args_for_item_schema(true),
            ),
        ));
    }

    // Handle GET requests to retrieve movies
    public function get_movies($request) {
        $args = array(
            'post_type' => 'movie',
            'posts_per_page' => -1,
        );

        $query = new WP_Query($args);
        $movies = array();

        foreach ($query->posts as $post) {
            $movies[] = $this->prepare_item_for_response($post, $request);
        }

        return new WP_REST_Response($movies, 200);
    }

    // Check permissions for getting movies
    public function get_movies_permissions_check($request) {
        return true; // Allow access for all users
    }

    // Handle POST requests to create a movie
    public function create_movie($request) {
        $title = sanitize_text_field($request->get_param('title'));

        $post_id = wp_insert_post(array(
            'post_title' => $title,
            'post_type' => 'movie',
            'post_status' => 'publish',
        ));

        if (is_wp_error($post_id)) {
            return new WP_Error('movie_creation_failed', 'Failed to create movie', array('status' => 500));
        }

        $post = get_post($post_id);
        return $this->prepare_item_for_response($post, $request);
    }

    // Check permissions for creating movies
    public function create_movie_permissions_check($request) {
        return current_user_can('edit_posts'); // Allow only editors and admins
    }

    // Prepare response data
    protected function prepare_item_for_response($post, $request) {
        $data = array(
            'id' => $post->ID,
            'title' => $post->post_title,
        );

        return $data;
    }
}

// Initialize the controller
function movie_rest_controller_init() {
    $controller = new Movie_Library_REST_Controller();
    $controller->register_routes();
}

add_action('rest_api_init', 'movie_rest_controller_init');

  • WP_REST_Controller: The Movie_REST_Controller extends WP_REST_Controller, which provides helpful methods for building RESTful APIs in WordPress.
  • register_routes: This method registers the routes for the movies endpoint, handling both GET (for retrieving movies) and POST (for creating a new movie) requests.
  • get_movies & create_movie: These methods handle the logic for retrieving and creating movies, respectively.
  • Permission Callbacks: The permission callbacks ensure that only authorized users can perform certain actions (e.g., creating a movie).

WP-CLI Packages

WP-CLI (WordPress Command Line Interface) is a powerful tool for managing WordPress sites from the command line. One of its most powerful features is the ability to extend its functionality through custom packages. WP-CLI packages are essentially plugins that add new commands or enhance existing ones.

A WP-CLI package is an external command or set of commands that can be installed globally via the WP-CLI package manager. These packages can perform a wide range of tasks, from managing databases to generating code scaffolds.

# syntax
# wp package install <package-name>

# example
wp package install wp-cli/i18n-command
wp package list

Useful package list

  • wp-cli/i18n-command: Manage translations and generate .pot files.
  • wp-cli/search-replace-command: Perform a search and replace on the database.
  • wp-cli/scaffold-command: Generate code scaffolding for custom post types, taxonomies, and more.
  • wp-cli/wp-super-cache-cli: Manage WP Super Cache settings and cache clearing from the command line.

WP-CLI Scaffold

WP-CLI provides a set of scaffold commands that generate code for different parts of a WordPress site, helping developers quickly set up various components.

Scaffold a Child Theme

Generates a new child theme based on an existing parent theme.

wp scaffold child-theme <slug> --parent_theme=<parent-slug>
  • --parent_theme=<parent-slug>: The slug of the parent theme (required).
  • --theme_name=<name>: The name of the theme.
  • --author=<author>: The author name.
  • --author_uri=<url>: The author’s website URL.
  • --theme_uri=<url>: The theme’s website URL.

Scaffold a Plugin

Generates the boilerplate code for a new WordPress plugin.

wp scaffold plugin <slug>
  • --plugin_name=<name>: The name of the plugin.
  • --plugin_description=<description>: A short description of the plugin.
  • --plugin_author=<author>: The author name.
  • --plugin_author_uri=<url>: The author’s website URL.
  • --plugin_uri=<url>: The plugin’s website URL.
  • --activate: Activate the plugin after creating it.
  • --force: Overwrite files if they already exist.

Scaffold a Post Type

Creates a custom post type with the necessary code to register it in WordPress.

wp scaffold post-type <slug> --label=<label>
  • --label=<label>: The name of the custom post type.
  • --textdomain=<textdomain>: The text domain for translations.
  • --theme: Generate the code in the current theme’s functions.php file.

Scaffold a Taxonomy

Generates code for registering a custom taxonomy.

wp scaffold taxonomy <slug> --post_type=<post_type>
  • --post_type=<post_type>: The post type to associate the taxonomy with (required).
  • --label=<label>: The name of the taxonomy.
  • --textdomain=<textdomain>: The text domain for translations.
  • --theme: Generate the code in the current theme’s functions.php file.
«
»

Leave a Reply

Your email address will not be published. Required fields are marked *