v1.0 Latest

CoreNexis WordPress REST API Plugin

Complete WordPress control through secure REST API with JWT authentication. Manage content, users, plugins, themes, and more programmatically without any configuration requirements.

JWT Authentication Content Management User Control Plugin Management Theme Control SEO & Meta Comment Moderation Zero Config
Download Plugin Documentation https://yoursite.com/wp-json/corenexis/v1

Latest WordPress REST API Plugin. This is the most comprehensive WordPress REST API plugin with secure JWT authentication, complete CRUD operations, and no configuration requirements. Download now and start controlling your WordPress site programmatically.

WordPress REST API Plugin

The CoreNexis WordPress REST API Plugin transforms your WordPress site into a powerful API-driven platform. With secure JWT authentication and comprehensive endpoint coverage, you can programmatically manage every aspect of your WordPress site without any configuration changes.

Key Features

  • JWT Authentication - Secure token-based authentication with configurable expiration
  • Complete CRUD Operations - Full control over posts, pages, categories, tags, and custom post types
  • User Management - Create, update, delete, and manage WordPress users with role-based access
  • Plugin Control - Install, activate, deactivate, and delete plugins remotely
  • Theme Management - Switch and update themes programmatically
  • Comment Moderation - Approve, unapprove, and delete comments via API
  • SEO & Meta Management - Complete control over SEO metadata, custom fields, and slugs
  • URL Lookup Functions - Convert URLs to post/page IDs and vice versa
  • Site Settings - Update WordPress settings and configurations
  • Security Features - Capability checking, input sanitization, and secure token storage
  • Zero Configuration - No need to modify wp-config.php or .htaccess files
  • SEO Plugin Compatibility - Works with Yoast SEO and All in One SEO

Base URL Structure

Base URL
https://yoursite.com/wp-json/corenexis/v1

Requirements

  • WordPress 5.0 or higher
  • PHP 7.4 or higher
  • MySQL 5.6 or higher
  • WordPress REST API enabled (default in WordPress)

Installation

Install the CoreNexis WordPress REST API Plugin using one of the methods below. The plugin is designed to work immediately after activation with no configuration required.

Method 1: Download from CoreNexis

  1. Download the plugin ZIP file from CoreNexis WordPress Plugin Page
  2. Go to your WordPress Admin → Plugins → Add New
  3. Click "Upload Plugin" and select the downloaded ZIP file
  4. Click "Install Now" and then "Activate"

Installation Complete. After activation, you'll see a new menu item "CoreNexis REST API" under Tools in your WordPress admin. No additional configuration is required!

Setup & Configuration

The plugin requires no configuration changes to your WordPress installation. Simply generate an API token and start using the endpoints immediately.

Generating API Tokens

  1. Go to WordPress Admin → Tools → CoreNexis REST API
  2. Click "Generate API Token"
  3. Choose token expiration:
    • 1 Day - For testing and short-term use
    • 1 Month - For development projects
    • 1 Year - For production applications
    • Never Expire - For permanent API access
  4. Copy the generated token and store it securely

Sample API Token

Your generated token will look like this:

Sample API Token
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3lvdXJzaXRlLmNvbSIsImlhdCI6MTY5...

Token Management

The admin interface provides complete token management capabilities:

  • View Active Tokens - See all active tokens with expiration dates
  • Revoke Tokens - Instantly revoke any token for security
  • Token Status - Monitor token usage and validity
  • One-Click Copy - Easily copy tokens for use in applications

Token Security. Store your API tokens securely and never share them publicly. Tokens provide full access to your WordPress site based on the user's capabilities who generated them.

Authentication

All API endpoints (except the login endpoint) require JWT token authentication. Tokens must be included in the Authorization header of every request.

Authentication Header

Include the following header in all API requests:

Authorization Header
Authorization: Bearer YOUR_ACCESS_TOKEN

Token-Based Authentication Flow

  1. Generate Token - Create a token via WordPress admin or login endpoint
  2. Include in Requests - Add Authorization header to all API calls
  3. Token Validation - Each request validates the token automatically
  4. Capability Checking - Actions are authorized based on user capabilities

Alternative: Login Endpoint Authentication

You can also obtain tokens programmatically using the login endpoint:

curl -X POST "https://yoursite.com/wp-json/corenexis/v1/login" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin",
    "password": "yourpassword"
  }'
{
  "success": true,
  "data": {
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
    "expires_in": "30 days",
    "user_id": 1,
    "user_login": "admin",
    "user_display_name": "Administrator",
    "user_capabilities": ["manage_options", "edit_posts", "publish_posts"]
  }
}

API Endpoints

The plugin provides comprehensive REST API endpoints covering all aspects of WordPress management. All endpoints follow RESTful conventions and return consistent JSON responses.

Authentication Endpoints

Manage user authentication and token operations.

MethodEndpointDescription
POST /login Login with username/password to get JWT token
POST /logout Logout and invalidate current token
GET /token/validate Validate current token and check expiration
GET /token/info Get detailed token information and user data

User Management Endpoints

Complete user lifecycle management with role-based access control.

MethodEndpointDescription
GET /users List all users with pagination and filtering
POST /users Create a new user with specified role and data
PUT /users/{id} Update user information, role, and metadata
DELETE /users/{id} Delete user (requires appropriate capabilities)
POST /users/check Check if user exists by username or email

User Deletion Warning. CAUTION: The user deletion endpoint can permanently delete users from your WordPress site. While WordPress has built-in protections and this feature is typically disabled by default, use this endpoint with extreme care. Always backup your database before performing user deletion operations.

Content Management Endpoints

Full CRUD operations for posts, pages, categories, and tags.

MethodEndpointDescription
GET /posts List posts with pagination, filtering, and search
POST /posts Create new post with content, meta, and settings
PUT /posts/{id} Update existing post content and metadata
DELETE /posts/{id} Delete post (moves to trash or permanent deletion)
GET /pages List pages with hierarchy and template information
POST /pages Create new page with parent, template, and settings
PUT /pages/{id} Update page content, hierarchy, and settings
DELETE /pages/{id} Delete page and update menu structures
GET /categories List categories with hierarchy and post counts
POST /categories Create new category with parent and metadata
PUT /categories/{id} Update category information and hierarchy
DELETE /categories/{id} Delete category and reassign posts
GET /tags List tags with usage statistics
POST /tags Create new tag with metadata
PUT /tags/{id} Update tag information and metadata
DELETE /tags/{id} Delete tag and remove from posts

Meta & SEO Management

Complete control over SEO metadata, custom fields, and slugs with support for popular SEO plugins.

MethodEndpointDescription
GET /posts/{id}/meta Get post SEO metadata and custom fields
POST /posts/{id}/meta Update post SEO metadata and custom fields
GET /pages/{id}/meta Get page SEO metadata and template settings
POST /pages/{id}/meta Update page SEO metadata and template settings
GET /categories/{id}/meta Get category SEO metadata and custom fields
POST /categories/{id}/meta Update category SEO metadata and custom fields
GET /tags/{id}/meta Get tag SEO metadata and custom fields
POST /tags/{id}/meta Update tag SEO metadata and custom fields

Supported Meta Fields

  • SEO Metadata: Title, description, keywords, robots directives
  • Open Graph: OG title, description, image, and type
  • Twitter Cards: Twitter-specific metadata
  • Custom Fields: Any custom meta fields for posts, pages, categories, and tags
  • Slug Management: Update permalinks and URL slugs
  • Yoast SEO: Compatible with Yoast SEO plugin fields
  • All in One SEO: Compatible with AIOSEO plugin fields

Comment Management

Moderate comments programmatically with approval workflows.

MethodEndpointDescription
GET /comments List comments with filtering by status and post
DELETE /comments/{id} Delete comment permanently or move to trash
POST /comments/{id}/approve Approve pending comment
POST /comments/{id}/unapprove Unapprove comment (move to pending)

Plugin Management

Install, activate, and manage WordPress plugins remotely.

MethodEndpointDescription
GET /plugins List all plugins with status and version info
POST /plugins/install Install plugin from WordPress repository
POST /plugins/activate Activate installed plugin
POST /plugins/deactivate Deactivate active plugin
POST /plugins/delete Delete plugin files permanently

Plugin Deletion Warning. EXTREME CAUTION: The plugin deletion endpoint will permanently remove plugin files from your WordPress installation. This action cannot be undone and may break your site if you delete critical plugins. WordPress typically has safeguards against plugin deletion, but use this endpoint with extreme care and always backup your site first.

Theme Management

Switch and update WordPress themes programmatically.

MethodEndpointDescription
GET /themes List all themes with status and details
POST /themes/activate Activate a different theme
POST /themes/update Update theme to latest version

Site Management

Manage WordPress site settings and configurations.

MethodEndpointDescription
GET /site/meta Get site metadata and settings
POST /site/meta Update site metadata and settings
GET /site/info Get WordPress version and basic site information

Lookup Functions

Utility endpoints for URL resolution and content discovery.

MethodEndpointDescription
POST /lookup/url Get post/page ID and type from URL
GET /lookup/recent Get recently published content
POST /lookup/by-slug Get content by slug (post name)

Code Examples

Comprehensive examples showing how to integrate with the WordPress REST API plugin using various programming languages and scenarios.

Authentication

cURL Examples

Login and Get Token

Login Request
curl -X POST "https://yoursite.com/wp-json/corenexis/v1/login" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin",
    "password": "yourpassword"
  }'

Validate Token

Token Validation
curl -X GET "https://yoursite.com/wp-json/corenexis/v1/token/validate" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Get Token Information

Token Info
curl -X GET "https://yoursite.com/wp-json/corenexis/v1/token/info" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

JavaScript Examples

Authentication Class
class WordPressAPI {
  constructor(baseURL) {
    this.baseURL = baseURL;
    this.token = localStorage.getItem('wp_api_token');
  }
  
  async login(username, password) {
    try {
      const response = await fetch(`${this.baseURL}/wp-json/corenexis/v1/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, password })
      });
      
      const data = await response.json();
      
      if (data.success) {
        this.token = data.data.token;
        localStorage.setItem('wp_api_token', this.token);
        console.log('Login successful!');
        console.log('Token expires in:', data.data.expires_in);
        console.log('User ID:', data.data.user_id);
        console.log('User login:', data.data.user_login);
        return data;
      } else {
        console.error('Login failed:', data.message);
        throw new Error(data.message);
      }
    } catch (error) {
      console.error('Login error:', error);
      throw error;
    }
  }
  
  async validateToken() {
    if (!this.token) {
      throw new Error('No token available');
    }
    
    try {
      const response = await fetch(`${this.baseURL}/wp-json/corenexis/v1/token/validate`, {
        headers: {
          'Authorization': `Bearer ${this.token}`
        }
      });
      
      const data = await response.json();
      
      if (data.success) {
        console.log('Token is valid');
        console.log('Expires:', data.data.expires);
        return true;
      } else {
        console.log('Token is invalid');
        this.logout();
        return false;
      }
    } catch (error) {
      console.error('Token validation error:', error);
      return false;
    }
  }
  
  async apiRequest(endpoint, method = 'GET', data = null) {
    if (!this.token) {
      throw new Error('Not authenticated. Please login first.');
    }
    
    const config = {
      method,
      headers: {
        'Authorization': `Bearer ${this.token}`,
        'Content-Type': 'application/json'
      }
    };
    
    if (data && (method === 'POST' || method === 'PUT')) {
      config.body = JSON.stringify(data);
    }
    
    try {
      const response = await fetch(`${this.baseURL}/wp-json/corenexis/v1${endpoint}`, config);
      const result = await response.json();
      
      if (!response.ok) {
        throw new Error(result.message || `HTTP ${response.status}`);
      }
      
      return result;
    } catch (error) {
      console.error(`API request failed (${method} ${endpoint}):`, error);
      throw error;
    }
  }
  
  logout() {
    this.token = null;
    localStorage.removeItem('wp_api_token');
    console.log('Logged out successfully');
  }
}

// Usage Example
const wp = new WordPressAPI('https://yoursite.com');

// Login
wp.login('admin', 'password').then(() => {
  console.log('Ready to make API calls!');
}).catch(error => {
  console.error('Login failed:', error);
});

Python Examples

WordPress API Client Class
import requests
import json
from typing import Optional, Dict, Any

class WordPressAPI:
    def __init__(self, base_url: str):
        self.base_url = base_url.rstrip('/')
        self.api_base = f"{self.base_url}/wp-json/corenexis/v1"
        self.token: Optional[str] = None
        self.session = requests.Session()
    
    def login(self, username: str, password: str) -> Dict[str, Any]:
        """Login and get JWT token"""
        url = f"{self.api_base}/login"
        data = {
            "username": username,
            "password": password
        }
        
        try:
            response = self.session.post(url, json=data, timeout=30)
            result = response.json()
            
            if response.status_code == 200 and result.get('success'):
                self.token = result['data']['token']
                self.session.headers.update({
                    'Authorization': f"Bearer {self.token}"
                })
                
                print("Login successful!")
                print(f"Token expires in: {result['data']['expires_in']}")
                print(f"User ID: {result['data']['user_id']}")
                print(f"User login: {result['data']['user_login']}")
                
                return result
            else:
                error_msg = result.get('message', 'Login failed')
                print(f"Login failed: {error_msg}")
                raise Exception(error_msg)
                
        except requests.RequestException as e:
            print(f"Login request failed: {e}")
            raise
    
    def validate_token(self) -> bool:
        """Validate current token"""
        if not self.token:
            print("No token available")
            return False
        
        try:
            response = self.session.get(f"{self.api_base}/token/validate", timeout=30)
            result = response.json()
            
            if response.status_code == 200 and result.get('success'):
                print("Token is valid")
                print(f"Expires: {result['data']['expires']}")
                return True
            else:
                print("Token is invalid")
                self.logout()
                return False
                
        except requests.RequestException as e:
            print(f"Token validation failed: {e}")
            return False
    
    def api_request(self, endpoint: str, method: str = 'GET', data: Optional[Dict] = None) -> Dict[str, Any]:
        """Make authenticated API request"""
        if not self.token:
            raise Exception("Not authenticated. Please login first.")
        
        url = f"{self.api_base}{endpoint}"
        
        try:
            if method.upper() == 'GET':
                response = self.session.get(url, timeout=30)
            elif method.upper() == 'POST':
                response = self.session.post(url, json=data, timeout=30)
            elif method.upper() == 'PUT':
                response = self.session.put(url, json=data, timeout=30)
            elif method.upper() == 'DELETE':
                response = self.session.delete(url, timeout=30)
            else:
                raise ValueError(f"Unsupported HTTP method: {method}")
            
            result = response.json()
            
            if not response.ok:
                error_msg = result.get('message', f'HTTP {response.status_code}')
                raise Exception(error_msg)
            
            return result
            
        except requests.RequestException as e:
            print(f"API request failed ({method} {endpoint}): {e}")
            raise
    
    def logout(self):
        """Clear token and session"""
        self.token = None
        self.session.headers.pop('Authorization', None)
        print("Logged out successfully")

# Usage Example
if __name__ == "__main__":
    wp = WordPressAPI('https://yoursite.com')
    
    try:
        # Login
        login_result = wp.login('admin', 'password')
        print("Ready to make API calls!")
        
        # Validate token
        if wp.validate_token():
            print("Token is valid, proceeding...")
        
    except Exception as e:
        print(f"Error: {e}")

PHP Examples

WordPress API Client Class
<?php
class WordPressAPI {
    private $baseUrl;
    private $apiBase;
    private $token;
    
    public function __construct($baseUrl) {
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->apiBase = $this->baseUrl . '/wp-json/corenexis/v1';
        $this->token = null;
    }
    
    public function login($username, $password) {
        $url = $this->apiBase . '/login';
        $data = [
            'username' => $username,
            'password' => $password
        ];
        
        $response = $this->makeRequest($url, 'POST', $data, false);
        
        if ($response && $response['success']) {
            $this->token = $response['data']['token'];
            
            echo "Login successful!\n";
            echo "Token expires in: {$response['data']['expires_in']}\n";
            echo "User ID: {$response['data']['user_id']}\n";
            echo "User login: {$response['data']['user_login']}\n";
            
            return $response;
        } else {
            $errorMsg = $response['message'] ?? 'Login failed';
            echo "Login failed: $errorMsg\n";
            throw new Exception($errorMsg);
        }
    }
    
    public function validateToken() {
        if (!$this->token) {
            echo "No token available\n";
            return false;
        }
        
        $url = $this->apiBase . '/token/validate';
        $response = $this->makeRequest($url, 'GET', null, true);
        
        if ($response && $response['success']) {
            echo "Token is valid\n";
            echo "Expires: {$response['data']['expires']}\n";
            return true;
        } else {
            echo "Token is invalid\n";
            $this->logout();
            return false;
        }
    }
    
    public function apiRequest($endpoint, $method = 'GET', $data = null) {
        if (!$this->token) {
            throw new Exception('Not authenticated. Please login first.');
        }
        
        $url = $this->apiBase . $endpoint;
        return $this->makeRequest($url, $method, $data, true);
    }
    
    private function makeRequest($url, $method, $data = null, $useAuth = false) {
        $ch = curl_init();
        
        $headers = ['Content-Type: application/json'];
        if ($useAuth && $this->token) {
            $headers[] = "Authorization: Bearer {$this->token}";
        }
        
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_FOLLOWLOCATION => true,
        ]);
        
        if ($data && in_array($method, ['POST', 'PUT'])) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        if ($curlError) {
            throw new Exception("cURL Error: $curlError");
        }
        
        $result = json_decode($response, true);
        
        if ($httpCode >= 400) {
            $errorMsg = $result['message'] ?? "HTTP $httpCode";
            throw new Exception($errorMsg);
        }
        
        return $result;
    }
    
    public function logout() {
        $this->token = null;
        echo "Logged out successfully\n";
    }
}

// Usage Example
try {
    $wp = new WordPressAPI('https://yoursite.com');
    
    // Login
    $loginResult = $wp->login('admin', 'password');
    echo "Ready to make API calls!\n";
    
    // Validate token
    if ($wp->validateToken()) {
        echo "Token is valid, proceeding...\n";
    }
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>

Content Management Examples

Create New Post

Create Post - cURL
curl -X POST "https://yoursite.com/wp-json/corenexis/v1/posts" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "My New Blog Post",
    "content": "This is the content of my new blog post with <strong>HTML</strong> formatting.",
    "status": "publish",
    "categories": [1, 5],
    "tags": ["wordpress", "api", "tutorial"],
    "featured_image": 123,
    "excerpt": "A brief summary of the post content."
  }'

Update Post with SEO Meta

Update Post Meta - JavaScript
// Update post SEO metadata
async function updatePostSEO(postId, seoData) {
  try {
    const response = await wp.apiRequest(`/posts/${postId}/meta`, 'POST', {
      meta_title: seoData.title,
      meta_description: seoData.description,
      meta_keywords: seoData.keywords,
      slug: seoData.slug,
      og_title: seoData.ogTitle,
      og_description: seoData.ogDescription,
      og_image: seoData.ogImage,
      robots_index: seoData.robotsIndex ? "1" : "0",
      robots_follow: seoData.robotsFollow ? "1" : "0",
      custom_fields: {
        custom_field_1: seoData.customField1,
        featured_color: seoData.featuredColor,
        external_link: seoData.externalLink
      }
    });
    
    if (response.success) {
      console.log('Post SEO updated successfully!');
      console.log('Post title:', response.data.title);
      console.log('New slug:', response.data.slug);
      console.log('SEO title:', response.data.meta_title);
    }
    
    return response;
  } catch (error) {
    console.error('Failed to update post SEO:', error);
    throw error;
  }
}

// Example usage
updatePostSEO(123, {
  title: "Complete WordPress REST API Guide - 2024",
  description: "Learn how to use WordPress REST API with JWT authentication for complete site control.",
  keywords: "wordpress, rest api, jwt, authentication, tutorial",
  slug: "wordpress-rest-api-guide-2024",
  ogTitle: "WordPress REST API Complete Guide",
  ogDescription: "Master WordPress REST API development",
  ogImage: "https://yoursite.com/wp-content/uploads/api-guide.jpg",
  robotsIndex: true,
  robotsFollow: true,
  customField1: "Featured Tutorial",
  featuredColor: "#fe5940",
  externalLink: "https://github.com/corenexis/wp-api-examples"
});

Bulk Content Operations

Bulk Operations - Python
def bulk_update_posts_category(wp_api, old_category_id, new_category_id):
    """Move all posts from one category to another"""
    try:
        # Get all posts in the old category
        posts_response = wp_api.api_request('/posts', 'GET', {
            'categories': old_category_id,
            'per_page': 100,
            'status': 'publish'
        })
        
        if posts_response['success']:
            posts = posts_response['data']
            print(f"📊 Found {len(posts)} posts to update")
            
            updated_count = 0
            for post in posts:
                # Remove old category and add new category
                current_categories = post.get('categories', [])
                if old_category_id in current_categories:
                    current_categories.remove(old_category_id)
                if new_category_id not in current_categories:
                    current_categories.append(new_category_id)
                
                # Update the post
                update_response = wp_api.api_request(f'/posts/{post["id"]}', 'PUT', {
                    'categories': current_categories
                })
                
                if update_response['success']:
                    updated_count += 1
                    print(f"Updated post: {post['title']['rendered']}")
                else:
                    print(f"Failed to update post: {post['title']['rendered']}")
            
            print(f"Successfully updated {updated_count} posts")
            return updated_count
        else:
            print("Failed to fetch posts")
            return 0
            
    except Exception as e:
        print(f"Bulk update failed: {e}")
        return 0

def create_posts_from_csv(wp_api, csv_file_path):
    """Create multiple posts from CSV file"""
    import csv
    
    try:
        with open(csv_file_path, 'r', encoding='utf-8') as file:
            reader = csv.DictReader(file)
            created_count = 0
            
            for row in reader:
                post_data = {
                    'title': row['title'],
                    'content': row['content'],
                    'status': row.get('status', 'draft'),
                    'excerpt': row.get('excerpt', ''),
                    'categories': [int(cat.strip()) for cat in row.get('categories', '').split(',') if cat.strip()],
                    'tags': [tag.strip() for tag in row.get('tags', '').split(',') if tag.strip()]
                }
                
                # Create the post
                response = wp_api.api_request('/posts', 'POST', post_data)
                
                if response['success']:
                    created_count += 1
                    post_id = response['data']['id']
                    print(f"Created post: {post_data['title']} (ID: {post_id})")
                    
                    # Add SEO meta if provided
                    if row.get('meta_title') or row.get('meta_description'):
                        meta_data = {}
                        if row.get('meta_title'):
                            meta_data['meta_title'] = row['meta_title']
                        if row.get('meta_description'):
                            meta_data['meta_description'] = row['meta_description']
                        if row.get('slug'):
                            meta_data['slug'] = row['slug']
                        
                        meta_response = wp_api.api_request(f'/posts/{post_id}/meta', 'POST', meta_data)
                        if meta_response['success']:
                            print(f"  Added SEO meta for post {post_id}")
                else:
                    print(f"Failed to create post: {post_data['title']}")
            
            print(f"Successfully created {created_count} posts from CSV")
            return created_count
            
    except Exception as e:
        print(f"CSV import failed: {e}")
        return 0

# Usage examples
if __name__ == "__main__":
    wp = WordPressAPI('https://yoursite.com')
    wp.login('admin', 'password')
    
    # Move all posts from category 5 to category 8
    bulk_update_posts_category(wp, 5, 8)
    
    # Create posts from CSV file
    create_posts_from_csv(wp, 'posts_to_import.csv')

User Management Examples

Create New User

Create User - cURL
curl -X POST "https://yoursite.com/wp-json/corenexis/v1/users" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "newuser123",
    "email": "newuser@example.com",
    "password": "SecurePassword123!",
    "first_name": "John",
    "last_name": "Doe",
    "role": "editor",
    "display_name": "John Doe",
    "description": "Content editor and blogger",
    "send_notification": true
  }'

User Creation Security. Creating users requires create_users capability. Always use strong passwords and appropriate roles. The API respects WordPress user creation limitations and security measures.

User Management Functions

User Management - JavaScript
class UserManager {
  constructor(wpAPI) {
    this.wp = wpAPI;
  }
  
  async createUser(userData) {
    try {
      const response = await this.wp.apiRequest('/users', 'POST', userData);
      
      if (response.success) {
        console.log('User created successfully!');
        console.log('User ID:', response.data.id);
        console.log('Email:', response.data.email);
        console.log('Role:', response.data.role);
        return response.data;
      }
    } catch (error) {
      console.error('Failed to create user:', error);
      throw error;
    }
  }
  
  async updateUserRole(userId, newRole) {
    try {
      const response = await this.wp.apiRequest(`/users/${userId}`, 'PUT', {
        role: newRole
      });
      
      if (response.success) {
        console.log(`User ${userId} role updated to ${newRole}`);
        return response.data;
      }
    } catch (error) {
      console.error('Failed to update user role:', error);
      throw error;
    }
  }
  
  async getUsersByRole(role) {
    try {
      const response = await this.wp.apiRequest('/users', 'GET', {
        role: role,
        per_page: 100
      });
      
      if (response.success) {
        console.log(`Found ${response.data.length} users with role: ${role}`);
        return response.data;
      }
    } catch (error) {
      console.error('Failed to fetch users:', error);
      throw error;
    }
  }
  
  async checkUserExists(identifier) {
    try {
      const response = await this.wp.apiRequest('/users/check', 'POST', {
        identifier: identifier // can be username or email
      });
      
      if (response.success) {
        console.log('User exists:', response.data.exists);
        if (response.data.exists) {
          console.log('Email:', response.data.user.email);
          console.log('Role:', response.data.user.role);
        }
        return response.data;
      }
    } catch (error) {
      console.error('Failed to check user:', error);
      throw error;
    }
  }
  
  async bulkUpdateUsers(userIds, updateData) {
    console.log(`Updating ${userIds.length} users...`);
    const results = [];
    
    for (const userId of userIds) {
      try {
        const response = await this.wp.apiRequest(`/users/${userId}`, 'PUT', updateData);
        if (response.success) {
          console.log(`Updated user ${userId}`);
          results.push({ userId, success: true, data: response.data });
        }
      } catch (error) {
        console.error(`Failed to update user ${userId}:`, error);
        results.push({ userId, success: false, error: error.message });
      }
    }
    
    const successCount = results.filter(r => r.success).length;
    console.log(`Successfully updated ${successCount}/${userIds.length} users`);
    return results;
  }
}

// Usage Example
const userManager = new UserManager(wp);

// Create a new editor
userManager.createUser({
  username: 'editor123',
  email: 'editor@example.com',
  password: 'SecurePass123!',
  first_name: 'Jane',
  last_name: 'Editor',
  role: 'editor',
  display_name: 'Jane Editor'
});

// Get all subscribers
userManager.getUsersByRole('subscriber').then(subscribers => {
  console.log('Subscribers:', subscribers);
});

// Check if user exists
userManager.checkUserExists('admin@example.com');

CRITICAL WARNING - User Deletion. EXTREME CAUTION REQUIRED: This plugin includes user deletion capabilities that can permanently remove users from your WordPress site. While WordPress typically disables user deletion by default and has built-in safeguards, this functionality should be used with utmost care. Always backup your database before attempting user deletion operations. Deleted users cannot be recovered easily.

Plugin Management Examples

List All Plugins

List Plugins - cURL
curl -X GET "https://yoursite.com/wp-json/corenexis/v1/plugins" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Install and Activate Plugin

Install Plugin - cURL
# Install plugin from WordPress repository
curl -X POST "https://yoursite.com/wp-json/corenexis/v1/plugins/install" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "slug": "contact-form-7"
  }'

# Activate the installed plugin
curl -X POST "https://yoursite.com/wp-json/corenexis/v1/plugins/activate" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "plugin": "contact-form-7/wp-contact-form-7.php"
  }'

Plugin Management Class

Plugin Manager - Python
class PluginManager:
    def __init__(self, wp_api):
        self.wp = wp_api
    
    def list_plugins(self):
        """Get list of all plugins with their status"""
        try:
            response = self.wp.api_request('/plugins', 'GET')
            
            if response['success']:
                plugins = response['data']
                print(f"📊 Found {len(plugins)} plugins:")
                
                active_count = 0
                inactive_count = 0
                
                for plugin in plugins:
                    status = "Active" if plugin['active'] else "⚪ Inactive"
                    print(f"  {status} - {plugin['name']} v{plugin['version']}")
                    
                    if plugin['active']:
                        active_count += 1
                    else:
                        inactive_count += 1
                
                print(f"\n📈 Summary: {active_count} active, {inactive_count} inactive")
                return plugins
            else:
                print("Failed to fetch plugins")
                return []
                
        except Exception as e:
            print(f"Error listing plugins: {e}")
            return []
    
    def install_plugin(self, slug):
        """Install plugin from WordPress repository"""
        try:
            print(f"Installing plugin: {slug}")
            response = self.wp.api_request('/plugins/install', 'POST', {
                'slug': slug
            })
            
            if response['success']:
                print(f"Plugin {slug} installed successfully!")
                plugin_info = response['data']
                print(f"Plugin: {plugin_info['name']}")
                print(f"Version: {plugin_info['version']}")
                print(f"Author: {plugin_info['author']}")
                return plugin_info
            else:
                print(f"Failed to install plugin {slug}: {response['message']}")
                return None
                
        except Exception as e:
            print(f"Error installing plugin {slug}: {e}")
            return None
    
    def activate_plugin(self, plugin_file):
        """Activate an installed plugin"""
        try:
            print(f"Activating plugin: {plugin_file}")
            response = self.wp.api_request('/plugins/activate', 'POST', {
                'plugin': plugin_file
            })
            
            if response['success']:
                print(f"Plugin {plugin_file} activated successfully!")
                return True
            else:
                print(f"Failed to activate plugin {plugin_file}: {response['message']}")
                return False
                
        except Exception as e:
            print(f"Error activating plugin {plugin_file}: {e}")
            return False
    
    def deactivate_plugin(self, plugin_file):
        """Deactivate an active plugin"""
        try:
            print(f" Deactivating plugin: {plugin_file}")
            response = self.wp.api_request('/plugins/deactivate', 'POST', {
                'plugin': plugin_file
            })
            
            if response['success']:
                print(f"Plugin {plugin_file} deactivated successfully!")
                return True
            else:
                print(f"Failed to deactivate plugin {plugin_file}: {response['message']}")
                return False
                
        except Exception as e:
            print(f"Error deactivating plugin {plugin_file}: {e}")
            return False
    
    def delete_plugin(self, plugin_file):
        """DELETE PLUGIN PERMANENTLY - USE WITH EXTREME CAUTION"""
        print("  WARNING: This will permanently delete the plugin files!")
        print(f"  Plugin to delete: {plugin_file}")
        
        # Extra confirmation for safety
        confirmation = input("  Type 'DELETE' to confirm plugin deletion: ")
        if confirmation != 'DELETE':
            print("Plugin deletion cancelled for safety")
            return False
        
        try:
            print(f" Deleting plugin: {plugin_file}")
            response = self.wp.api_request('/plugins/delete', 'POST', {
                'plugin': plugin_file
            })
            
            if response['success']:
                print(f"Plugin {plugin_file} deleted permanently!")
                print("  Remember: This action cannot be undone!")
                return True
            else:
                print(f"Failed to delete plugin {plugin_file}: {response['message']}")
                return False
                
        except Exception as e:
            print(f"Error deleting plugin {plugin_file}: {e}")
            return False
    
    def install_and_activate(self, slug):
        """Install and activate plugin in one operation"""
        # First install the plugin
        plugin_info = self.install_plugin(slug)
        if not plugin_info:
            return False
        
        # Find the main plugin file (usually slug/slug.php)
        plugin_file = f"{slug}/{slug}.php"
        
        # Activate the plugin
        return self.activate_plugin(plugin_file)
    
    def bulk_plugin_operations(self, operations):
        """Perform multiple plugin operations"""
        results = []
        
        for operation in operations:
            action = operation['action']
            plugin = operation.get('plugin', operation.get('slug'))
            
            try:
                if action == 'install':
                    result = self.install_plugin(plugin)
                    results.append({'action': action, 'plugin': plugin, 'success': bool(result)})
                elif action == 'activate':
                    result = self.activate_plugin(plugin)
                    results.append({'action': action, 'plugin': plugin, 'success': result})
                elif action == 'deactivate':
                    result = self.deactivate_plugin(plugin)
                    results.append({'action': action, 'plugin': plugin, 'success': result})
                elif action == 'delete':
                    result = self.delete_plugin(plugin)
                    results.append({'action': action, 'plugin': plugin, 'success': result})
                else:
                    print(f" Unknown action: {action}")
                    results.append({'action': action, 'plugin': plugin, 'success': False})
                    
            except Exception as e:
                print(f"Error with {action} on {plugin}: {e}")
                results.append({'action': action, 'plugin': plugin, 'success': False, 'error': str(e)})
        
        # Summary
        successful = len([r for r in results if r['success']])
        print(f"\n Bulk operations complete: {successful}/{len(results)} successful")
        
        return results

# Usage Examples
if __name__ == "__main__":
    wp = WordPressAPI('https://yoursite.com')
    wp.login('admin', 'password')
    
    plugin_manager = PluginManager(wp)
    
    # List all plugins
    plugins = plugin_manager.list_plugins()
    
    # Install and activate a plugin
    plugin_manager.install_and_activate('contact-form-7')
    
    # Bulk operations
    operations = [
        {'action': 'install', 'slug': 'yoast-seo'},
        {'action': 'install', 'slug': 'jetpack'},
        {'action': 'activate', 'plugin': 'yoast-seo/wp-seo.php'},
        {'action': 'activate', 'plugin': 'jetpack/jetpack.php'}
    ]
    
    plugin_manager.bulk_plugin_operations(operations)

EXTREME WARNING - Plugin Deletion. CRITICAL DANGER: The plugin deletion endpoint can permanently destroy plugin files and potentially break your WordPress site. While WordPress has built-in protections and typically disables plugin deletion, this functionality bypasses normal restrictions. NEVER use plugin deletion without: 1) Complete site backup, 2) Understanding the consequences, 3) Testing in staging environment first. Plugin deletion CANNOT BE UNDONE and may require manual file recovery or site restoration.

Security

The CoreNexis WordPress REST API Plugin implements multiple security layers to protect your WordPress site while providing powerful remote access capabilities.

Security Features

JWT Authentication

Secure, stateless token-based authentication

Capability Checking

Respects WordPress user permissions and roles

Token Expiration

Configurable token lifetimes from 1 day to permanent

Token Revocation

Instant token invalidation for security breaches

Secure Storage

Encrypted token storage in WordPress database

Input Sanitization

All inputs properly validated and sanitized

WordPress Capabilities Required

The plugin respects WordPress's built-in capability system. Different endpoints require specific capabilities:

OperationRequired CapabilityTypical Roles
User Managementlist_users, create_users, edit_users, delete_usersAdministrator
Content Managementpublish_posts, edit_posts, delete_postsEditor, Author, Administrator
Plugin Managementinstall_plugins, activate_plugins, delete_pluginsAdministrator only
Theme Managementswitch_themes, update_themesAdministrator only
Comment Moderationmoderate_commentsEditor, Administrator
Site Settingsmanage_optionsAdministrator only

Security Best Practices

  1. Token Management
    • Use appropriate token expiration times
    • Revoke tokens immediately if compromised
    • Generate new tokens for production vs development
    • Store tokens securely in your applications
  2. User Access Control
    • Generate tokens with users who have minimum required capabilities
    • Avoid using administrator accounts for routine operations
    • Regularly audit user permissions and token usage
  3. Network Security
    • Always use HTTPS for API requests
    • Implement IP restrictions where possible
    • Monitor API usage for unusual patterns
    • Use proper firewall rules
  4. Backup Strategy
    • Always backup before using destructive operations
    • Test API operations in staging environment first
    • Keep recent database backups available

WordPress Security Integration. This plugin integrates seamlessly with WordPress's existing security features including user roles, capabilities, nonces, and input sanitization. It does not bypass WordPress security - it works within it.

Error Handling

The plugin provides consistent, detailed error responses to help you handle different scenarios and debug issues effectively.

HTTP Status Codes

Status CodeError TypeExample Response
200Success{"success": true, "data": {...}}
400Bad Request{"success": false, "message": "Invalid request parameters", "error_code": "INVALID_PARAMS"}
401Unauthorized{"success": false, "message": "Invalid or expired token", "error_code": "INVALID_TOKEN"}
403Forbidden{"success": false, "message": "Insufficient permissions", "error_code": "INSUFFICIENT_PERMISSIONS"}
404Not Found{"success": false, "message": "Post not found", "error_code": "POST_NOT_FOUND"}
422Validation Error{"success": false, "message": "Invalid email format", "error_code": "VALIDATION_ERROR"}
500Server Error{"success": false, "message": "Internal server error", "error_code": "SERVER_ERROR"}

Common Error Codes

Error CodeDescription
INVALID_TOKENJWT token is invalid, expired, or malformed
TOKEN_EXPIREDJWT token has expired and needs renewal
INSUFFICIENT_PERMISSIONSUser doesn't have required WordPress capabilities
INVALID_LOGINUsername or password is incorrect
USER_NOT_FOUNDRequested user ID doesn't exist
POST_NOT_FOUNDRequested post/page ID doesn't exist
PLUGIN_NOT_FOUNDPlugin slug or file doesn't exist
VALIDATION_ERRORInput data failed validation rules
OPERATION_FAILEDWordPress operation failed (e.g., couldn't save post)
PLUGIN_INSTALL_FAILEDPlugin installation from repository failed

Error Response Format

All error responses follow a consistent JSON structure:

Error Response Structure
{
  "success": false,
  "message": "Human-readable error description",
  "error_code": "MACHINE_READABLE_ERROR_CODE",
  "data": {
    "additional_info": "Optional additional error details",
    "validation_errors": ["Array of specific validation errors if applicable"]
  },
  "timestamp": "2024-01-15 10:30:45"
}

Error Handling Best Practices

  • Always check the success field before processing response data
  • Use error_code for programmatic error handling
  • Display message field to users for context
  • Implement retry logic for temporary failures (5xx errors)
  • Handle token expiration gracefully with automatic renewal
Error Handling Example
async function handleAPIResponse(response) {
  try {
    const data = await response.json();
    
    if (data.success) {
      // Handle successful response
      console.log('Operation successful:', data.data);
      return data.data;
    } else {
      // Handle error response
      console.error('Operation failed:', data.message);
      
      switch (data.error_code) {
        case 'INVALID_TOKEN':
        case 'TOKEN_EXPIRED':
          // Token issues - try to refresh or redirect to login
          console.log('Token issue, attempting refresh...');
          await refreshToken();
          break;
          
        case 'INSUFFICIENT_PERMISSIONS':
          // Permission denied - show appropriate message
          showError('You don\'t have permission for this operation');
          break;
          
        case 'VALIDATION_ERROR':
          // Show validation errors to user
          if (data.data?.validation_errors) {
            showValidationErrors(data.data.validation_errors);
          }
          break;
          
        default:
          // Generic error handling
          showError(data.message);
      }
      
      throw new Error(data.message);
    }
  } catch (error) {
    console.error('Response parsing failed:', error);
    throw error;
  }
}

Download Plugin

Download the CoreNexis WordPress REST API Plugin and start controlling your WordPress site programmatically with secure JWT authentication.

What's Included

  • Complete Plugin Files - Ready-to-install WordPress plugin
  • Admin Interface - Beautiful token management interface
  • Documentation - Comprehensive README and inline docs
  • Code Examples - Sample implementations in multiple languages
  • Security Features - Built-in JWT authentication and capability checking

Installation Requirements

RequirementSpecification
WordPress Version5.0 or higher (tested up to 6.4)
PHP Version7.4 or higher (PHP 8.0+ recommended)
MySQL Version5.6 or higher (MySQL 8.0+ recommended)
Server RequirementsStandard WordPress hosting with REST API enabled
ConfigurationNo wp-config.php or .htaccess changes required

Ready to Get Started? Download the plugin now and have your WordPress REST API running in minutes. No complex configuration required - just activate and generate your first API token!

Support & Resources

Get help with installation, configuration, and development using the CoreNexis WordPress REST API Plugin. Our team provides comprehensive support for all users.

Support Channels

Documentation & Resources

ResourceDescription
Code ExamplesReady-to-use code samples in multiple programming languages
API ReferenceComplete endpoint reference with parameters and responses
Best Practices GuideSecurity recommendations and optimization tips
Migration GuideHelp with migrating from other WordPress API solutions

Professional Services

Need custom development or integration assistance? Our team offers professional services:

  • Custom Integration - Tailored API integration for your specific needs
  • Performance Optimization - Optimize your WordPress site for API usage
  • Security Audits - Review and enhance your API security setup
  • Training & Consultation - Team training on WordPress REST API development
  • Custom Endpoints - Development of specialized API endpoints
  • Migration Services - Complete migration from other API solutions

Frequently Asked Questions

Do I need to modify wp-config.php or .htaccess?

No! The plugin works out of the box without any configuration file changes. Simply activate and start using.

Is this plugin compatible with other security plugins?

Yes, the plugin works alongside most WordPress security plugins. It uses WordPress's built-in security features and doesn't conflict with standard security measures.

Can I use this with WordPress multisite?

Yes, the plugin supports WordPress multisite installations. Each site in the network can have its own API tokens and settings.

How do I backup before using destructive operations?

Always create a complete site backup before using user deletion or plugin deletion endpoints. Use your hosting provider's backup tools or WordPress backup plugins.

What happens if my token is compromised?

Immediately revoke the compromised token through the WordPress admin interface (Tools → CoreNexis REST API) and generate a new one. The revocation is instant.

Can I limit API access to specific IP addresses?

While the plugin doesn't have built-in IP restriction, you can implement this at the server level using .htaccess rules or your hosting provider's security features.

Need More Help? Can't find the answer you're looking for? Our support team is here to help! Send us an email with your specific question and we'll get back to you within 24 hours.

Stay in the loop

New APIs, features and offers, straight to your inbox. No spam.

Already subscribed? Manage preferences