C#程序创建WordPress产品后,如何调用Regenerate Thumbnails插件生成缩略图?
Hey there! Let's tackle your thumbnail issue—great job getting the products and associated images showing up already, that's half the battle. Here are two reliable ways to fix those missing thumbnails, either by calling the Regenerate Thumbnails plugin via a custom PHP script or triggering it directly from your C# app:
1. Create a Custom PHP Script to Call Regenerate Thumbnails
Regenerate Thumbnails exposes internal functions you can leverage in a custom PHP file. This acts as a secure bridge between your C# app and WordPress.
Step 1: Add the PHP Script to Your WordPress Root
Create a file named regenerate-product-thumbnails.php in your WordPress installation's root directory, with this code:
<?php // Load WordPress core to access plugin functions require_once('wp-load.php'); // Security check: Add a secret key to block unauthorized calls $allowed_secret = 'your-unique-secure-key-here'; // Replace with a strong, unique string if (!isset($_GET['secret']) || $_GET['secret'] !== $allowed_secret) { wp_die('Unauthorized access.'); } // Verify Regenerate Thumbnails is active if (!class_exists('Regenerate_Thumbnails')) { wp_send_json_error('Regenerate Thumbnails plugin is not activated.'); } // Get the target product post ID from the request $post_id = (int)($_GET['post_id'] ?? 0); if ($post_id === 0) { wp_send_json_error('No post ID provided.'); } // Initialize the regenerator and process the post $regenerator = new Regenerate_Thumbnails(); $regeneration_result = $regenerator->regenerate_thumbnails_for_post($post_id); // Return the result as JSON for your C# app to parse if ($regeneration_result['success']) { wp_send_json_success([ 'message' => "Thumbnails regenerated successfully for post #{$post_id}", 'generated_thumbnails' => $regeneration_result['thumbnails'] ]); } else { wp_send_json_error([ 'message' => "Failed to regenerate thumbnails: {$regeneration_result['error']}" ]); } ?>
Step 2: Secure the Script
Don't skip the secret parameter! Generate a unique, strong key and use it to restrict access to only your C# app—this prevents random people from hitting your script.
2. Call the PHP Script from Your C# App
Now you can trigger thumbnail regeneration directly from your C# desktop app using an HTTP request. Here's a clean example using HttpClient:
using System; using System.Net.Http; using System.Threading.Tasks; public class WordPressThumbnailHandler { private readonly HttpClient _httpClient; private readonly string _wpBaseUrl; private readonly string _secureSecret; public WordPressThumbnailHandler(string wordPressBaseUrl, string secureSecretKey) { _httpClient = new HttpClient(); _wpBaseUrl = wordPressBaseUrl; _secureSecret = secureSecretKey; } public async Task RegenerateThumbnailsForProductAsync(int productPostId) { try { // Build the request URL with required security and post ID parameters var requestUrl = $"{_wpBaseUrl}/regenerate-product-thumbnails.php?" + $"secret={Uri.EscapeDataString(_secureSecret)}&" + $"post_id={productPostId}"; var response = await _httpClient.GetAsync(requestUrl); response.EnsureSuccessStatusCode(); var resultJson = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Regeneration result for product {productPostId}: {resultJson}"); } catch (HttpRequestException ex) { Console.WriteLine($"Error connecting to WordPress: {ex.Message}"); } } } // Usage example in your app // var thumbnailHandler = new WordPressThumbnailHandler("https://your-wp-site.com", "your-secure-key"); // await thumbnailHandler.RegenerateThumbnailsForProductAsync(123); // Replace 123 with your product's post ID
Alternative: Use WP-CLI (If You Have Server Access)
If your WordPress server has WP-CLI installed, you could also trigger regeneration via a command line call from your C# app. This is useful if you prefer not to add a custom PHP script:
// Example using SSH.NET to run WP-CLI on your server using Renci.SshNet; public async Task RegenerateWithWpCliAsync(string serverIp, string sshUsername, string sshPassword, int productPostId) { using (var sshClient = new SshClient(serverIp, sshUsername, sshPassword)) { sshClient.Connect(); var wpCliCommand = sshClient.CreateCommand($"cd /path/to/your/wordpress && wp media regenerate --post_id={productPostId} --yes"); var commandOutput = wpCliCommand.Execute(); Console.WriteLine("WP-CLI regeneration output: " + commandOutput); sshClient.Disconnect(); } }
Key Notes
- Test the PHP script first in your browser (with the correct secret and post ID) to confirm it works before integrating with C#.
- Keep your secret key secure—never hardcode it in public repositories or share it.
- If you're using a newer version of Regenerate Thumbnails, double-check the plugin's internal function names (they rarely change, but it's safe to verify).
内容的提问来源于stack exchange,提问作者MareCieco

