WP-CLI: More Useful Commands
WP-CLI continues to prove itself as an indispensable tool, streamlining complex tasks into simple command-line operations. We’ve covered some essential WP-CLI commands before, but there are a few more gems that can significantly enhance your workflow.
1. Database Management
Managing your WordPress database becomes a breeze with WP-CLI. Here are a couple of powerful commands:
- Export Database:
wp db export my-database.sql
This command exports your entire database to an SQL file. Perfect for backups or migrating your site.
- Search and Replace:
wp search-replace 'http://oldsite.com' 'http://newsite.com'
Quickly replace URLs or other text in your database. This is especially useful when moving a site from one domain to another.
2. Cache Management
Dealing with cache can be tricky, but WP-CLI simplifies it:
- Clear Cache:
wp cache flush
Instantly clear your WordPress cache with this command. Ideal for when you’ve made changes that aren’t showing up.
- Manage Object Cache:
wp cache get my-cache-key
wp cache set my-cache-key 'my-cache-value'
wp cache delete my-cache-key
Directly interact with the object cache, enabling you to get, set, or delete specific cache items.
3. Plugin and Theme Scaffolding
Creating custom plugins and themes is a core part of WordPress development. WP-CLI can help you scaffold them quickly:
- Generate Plugin:
wp scaffold plugin my-plugin
Kickstart your plugin development by generating the necessary files and folders with one command.
- Generate Child Theme:
wp scaffold child-theme my-child-theme --parent_theme=twentytwentyon
REST API: Enhancing Functionality
The WordPress REST API opens up endless possibilities for interacting with your WordPress site programmatically. Whether you’re building custom apps or integrating third-party services, understanding REST API authentication and extension is crucial.
1. Authentication with REST API
Authentication is a key aspect when working with the REST API, ensuring that only authorized users can access certain endpoints.
- Basic Authentication: Basic Authentication is the simplest method, where the user’s credentials are sent with each API request. While easy to implement, it’s not recommended for production use without HTTPS, as credentials are sent in plain text.
curl --user username:password https://example.com/wp-json/wp/v2/posts
- OAuth Authentication: OAuth provides a more secure method, allowing users to authorize third-party applications without sharing their credentials. Implementing OAuth involves setting up consumer keys and tokens, making it more complex but suitable for production environments.
- JWT Authentication: JSON Web Tokens (JWT) offer another secure way to authenticate API requests. Tokens are generated upon login and sent with each request, allowing the server to validate the user’s identity.
curl -X POST -H "Authorization: Bearer YOUR_TOKEN" https://example.com/wp-json/wp/v2/posts
2. Extend REST API
Extending the REST API allows you to create custom endpoints or modify existing ones, tailoring the API to your specific needs.
- Adding Custom Endpoints: You can create custom endpoints to expose new types of data or functionalities. For example, if you’re building a movie review site, you might add an endpoint to fetch reviews by a specific user.
add_action('rest_api_init', function () {
register_rest_route('myplugin/v1', '/reviews/(?P<user_id>\d+)', array(
'methods' => 'GET',
'callback' => 'get_reviews_by_user',
));
});
function get_reviews_by_user($data) {
// Fetch and return reviews based on user ID
}
- Modifying Existing Endpoints: You might need to alter the response of an existing endpoint to include additional data or change the structure. This can be done by hooking into the
rest_prepare_postfilter for the posts endpoint, for example.
add_filter('rest_prepare_post', 'modify_post_response', 10, 3);
function modify_post_response($response, $post, $request) {
$response->data['custom_field'] = get_post_meta($post->ID, 'custom_field', true);
return $response;
}
JWT with REST
we’ll will see on how to add JWT authentication to a custom REST API endpoint in WordPress.
Step 1: Install JWT Authentication Plugin
Incorporating JSON Web Tokens (JWT) for authentication can greatly enhance the security of your REST API endpoints. In this guide, we’ll walk through setting up JWT authentication for a custom REST API endpoint in WordPress using a class-based singleton approach. This method helps keep your code organized and ensures that only one instance of your authentication logic exists.
To get started with JWT authentication, you’ll first need to install a plugin that provides JWT support. One popular choice is the JWT Authentication for WP REST API plugin.
- Install the Plugin: You can install the plugin via the WordPress admin dashboard or by using WP-CLI:
wp plugin install jwt-authentication-for-wp-rest-api --activate
Configure the Plugin: After activation, you’ll need to configure the plugin by adding the following lines to your wp-config.php file:
define('JWT_AUTH_SECRET_KEY', 'your_secret_key_here');
define('JWT_AUTH_CORS_ENABLE', true);
Step 2: Create a Custom Endpoint
We’ll create a singleton class to handle JWT authentication and register a custom REST API endpoint. This approach ensures that the JWT authentication logic is centralized and only instantiated once.
Define the Singleton Class:
- Create a new PHP file, for example,
class-jwt-auth.php, and add the following code:
class JWT_Auth {
private static $instance = null;
private function __construct() {
add_action('rest_api_init', array($this, 'register_routes'));
}
public static function get_instance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function register_routes() {
register_rest_route('myplugin/v1', '/user-profile', array(
'methods' => 'GET',
'callback' => array($this, 'get_user_profile'),
'permission_callback' => array($this, 'check_jwt_auth'),
));
}
public function get_user_profile(WP_REST_Request $request) {
$user = wp_get_current_user();
if (empty($user) || !is_user_logged_in()) {
return new WP_Error('rest_forbidden', 'You are not allowed to access this resource.', array('status' => 403));
}
return array(
'ID' => $user->ID,
'username' => $user->user_login,
'email' => $user->user_email,
);
}
public function check_jwt_auth(WP_REST_Request $request) {
$auth_header = $request->get_header('Authorization');
if (!$auth_header || !preg_match('/Bearer\s(\S+)/', $auth_header, $matches)) {
return new WP_Error('rest_authentication_error', 'No token provided.', array('status' => 401));
}
$token = $matches[1];
$response = wp_remote_get("https://yourdomain.com/wp-json/jwt-auth/v1/token/validate?token={$token}");
if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
return new WP_Error('rest_authentication_error', 'Invalid token.', array('status' => 401));
}
return true;
}
}
// Initialize the singleton
JWT_Auth::get_instance();
JWT_AuthClass: This class implements the singleton pattern to ensure only one instance exists. It registers the custom endpoint and handles JWT validation.get_instanceMethod: Ensures that only one instance of the class is created.register_routesMethod: Registers the custom REST API route.get_user_profileMethod: Fetches user profile data if authentication is successful.check_jwt_authMethod: Validates the JWT provided in the request header.
Include the Singleton Class in Your Plugin or Theme:
Include the class-jwt-auth.php file in your plugin or theme:
require_once get_template_directory() . '/class-jwt-auth.php';
- djust the path if you’re using a plugin or different directory structure.
Step 3: Test the Endpoint
With JWT authentication set up, you can now test the custom REST API endpoint.
- Obtain a JWT Token: Use the following POST request to get a JWT token:
curl -X POST -d "username=yourusername&password=yourpassword" https://yourdomain.com/wp-json/jwt-auth/v1/token
This request will return a JWT token if the credentials are valid.
Access the Endpoint: Use the obtained JWT token to access your custom endpoint:
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" https://yourdomain.com/wp-json/myplugin/v1/user-profile
Replace YOUR_JWT_TOKEN with the actual token. A successful request will return the user’s profile information.
This is short example of how we can use JWT_TOKEN in WP plugin in a class based approach.
Thank you for reading…
By ~Leaveitblank (Mayank Tripathi)