如何在自定义PHP代码中调用WordPress函数及对接wp-invoice API
Hey there! Since your custom PHP app is hosted independently from the WordPress site running wp-invoice, you won't be able to directly include WordPress core files (like wp-load.php) to call its functions. Instead, the right approach is to use wp-invoice's REST API to fetch invoice data remotely. Here's a step-by-step breakdown tailored to your use case:
1. Confirm wp-invoice's REST API Support
First, verify that the wp-invoice plugin exposes a REST API (most modern WordPress plugins do this out of the box). Check the plugin's documentation to find the exact API endpoints you'll need—common ones include:
- Fetching a user's invoices (e.g.,
/wp-json/wp-invoice/v1/invoices) - Fetching a single invoice by ID (e.g.,
/wp-json/wp-invoice/v1/invoices/{id})
2. Set Up Cross-Server Authentication
To access user-specific invoices, you need to authenticate your PHP app's requests to the WordPress API. Two reliable methods for cross-server setups are:
Option A: JWT Authentication
- Install a JWT authentication plugin on your WordPress site to enable token-based auth.
- When a user logs into your PHP app, send their credentials (email/password) to WordPress's JWT login endpoint (e.g.,
/wp-json/jwt-auth/v1/token). You'll get a JSON Web Token (JWT) in response. - Include this token in the
Authorizationheader of all subsequent wp-invoice API requests.
Option B: API Key Authentication
- If wp-invoice supports API keys (check its docs), generate a unique API key in your WordPress admin panel.
- Include this key in your API requests—either as a query parameter (e.g.,
?api_key=your-key-here) or a custom request header (e.g.,X-API-Key: your-key-here).
3. Fetch Invoices in Your PHP Code
Use cURL (the most flexible option) to send authenticated requests to the wp-invoice API. Here's a working example:
// Replace these with your actual values $wordpress_base_url = 'https://your-wordpress-site.com'; $jwt_token = 'your-valid-jwt-token'; // From JWT auth step $user_id = 123; // Match the user's ID in your WordPress site // Build the API endpoint for fetching the user's invoices $invoice_api_url = $wordpress_base_url . '/wp-json/wp-invoice/v1/invoices?user_id=' . $user_id; // Initialize cURL request $ch = curl_init($invoice_api_url); // Set request headers with authentication curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $jwt_token, 'Content-Type: application/json' ]); // Return response as string instead of printing it curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute the request $response = curl_exec($ch); $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); // Handle the response if ($http_status === 200 && $response) { $invoices = json_decode($response, true); // Render invoices to your user (customize this to match your app's UI) echo '<h2>Your Invoices</h2>'; foreach ($invoices as $invoice) { echo '<div class="invoice-card">'; echo '<p><strong>Invoice #:</strong> ' . htmlspecialchars($invoice['number']) . '</p>'; echo '<p><strong>Date:</strong> ' . htmlspecialchars($invoice['date_created']) . '</p>'; echo '<p><strong>Total:</strong> ' . htmlspecialchars($invoice['total']) . '</p>'; echo '</div>'; } } else { // Handle errors (e.g., invalid token, no invoices found) switch ($http_status) { case 401: echo 'Error: Unauthorized access. Please check your authentication token.'; break; case 404: echo 'Error: Invoice API endpoint not found.'; break; default: echo 'Failed to load invoices. Please try again later.'; } }
4. Key Considerations for Security & Reliability
- Don't hardcode credentials: Store JWT tokens, API keys, and WordPress URLs in a secure config file or environment variables (never in your public code).
- Validate user identity: Ensure the user logged into your PHP app matches the user whose invoices you're fetching (use unique identifiers like email or linked user IDs).
- Handle CORS if needed: If your app is served from a different domain than WordPress, you may need to enable CORS on the WordPress site (via a plugin or custom
.htaccessrules). - Error handling: Always check HTTP status codes and handle failures gracefully for a better user experience.
内容的提问来源于stack exchange,提问作者ielaajez

