如何通过图片名称自动为WordPress自定义文章类型添加图片?
Got it, let's break this down and build a PHP script tailored for your Cron Job needs—one that matches your FTP-uploaded car photos to the corresponding "car" custom posts using their license plate custom field.
1. Core Logic Overview
Here's the step-by-step flow the script will follow:
- Load the WordPress environment to access post data and media functions
- Scan the
wp-uploads/car-photosfolder for images - Extract the license plate from each image's filename (e.g.,
311111from311111-photo-01.jpg) - Find the matching "car" post using the license plate custom field
- Add the image to WordPress's media library and link it to the post (e.g., set as featured image)
- Move processed images to a separate folder to avoid re-handling
2. Complete PHP Script
Save this as car-photo-importer.php (place it in your WordPress root directory or a secure, non-public folder):
<?php // Load WordPress core - update the path to match your WP installation require_once('/path/to/your/wp-load.php'); // Configuration settings $photos_directory = WP_CONTENT_DIR . '/uploads/car-photos/'; $processed_directory = WP_CONTENT_DIR . '/uploads/car-photos/processed/'; $custom_field_key = 'license_plate'; // Your custom field key for license plates $custom_post_type = 'car'; // Your custom post type slug // Create processed directory if it doesn't exist if (!file_exists($processed_directory)) { mkdir($processed_directory, 0755, true); } // Scan the photos directory if ($directory_handle = opendir($photos_directory)) { while (false !== ($file = readdir($directory_handle))) { // Skip directories and non-image files if ($file === "." || $file === ".." || !in_array(pathinfo($file, PATHINFO_EXTENSION), ['jpg', 'jpeg', 'png', 'gif'])) { continue; } // Extract license plate from filename (format: {license}-photo-{number}.ext) $filename_parts = explode('-', $file); if (count($filename_parts) < 3) { echo "Skipping invalid filename: $file\n"; continue; } $license_plate = $filename_parts[0]; // Find the matching car post $post_query = new WP_Query([ 'post_type' => $custom_post_type, 'meta_key' => $custom_field_key, 'meta_value' => $license_plate, 'posts_per_page' => 1, // Assume one post per license plate 'post_status' => 'publish' ]); if ($post_query->have_posts()) { while ($post_query->have_posts()) { $post_query->the_post(); $post_id = get_the_ID(); // Prepare image data for WordPress media library $file_path = $photos_directory . $file; $file_url = WP_CONTENT_URL . '/uploads/car-photos/' . $file; $file_mime = wp_check_filetype($file, null)['type']; // Insert image into media library $attachment_data = [ 'post_mime_type' => $file_mime, 'post_title' => sanitize_file_name($file), 'post_content' => '', 'post_status' => 'inherit' ]; $attachment_id = wp_insert_attachment($attachment_data, $file_path, $post_id); // Generate image thumbnails (requires WP's image processing tools) require_once(ABSPATH . 'wp-admin/includes/image.php'); $attachment_metadata = wp_generate_attachment_metadata($attachment_id, $file_path); wp_update_attachment_metadata($attachment_id, $attachment_metadata); // Set image as the post's featured image set_post_thumbnail($post_id, $attachment_id); echo "Success: Linked $file to post ID $post_id (License: $license_plate)\n"; } } else { echo "Warning: No car post found for license plate $license_plate (file: $file)\n"; } // Move processed image to avoid re-processing rename($file_path, $processed_directory . $file); } closedir($directory_handle); } else { echo "Error: Could not open directory $photos_directory\n"; } // Reset WordPress post data to avoid conflicts wp_reset_postdata(); ?>
3. Key Details & Customization Tips
- WordPress Path: Update the
wp-load.phppath if your script isn't in the WP root (e.g.,../wp-load.phpif it's in a subfolder). - Image Linking: If you don't want to set the image as a featured image, you could:
- Add a custom field to the post with the image URL
- Append the image to the post's content using
wp_update_post()
- Filename Flexibility: If your image filenames vary slightly, adjust the
explode('-', $file)logic to correctly extract the license plate. - Logging: The script outputs status messages—you can redirect these to a log file (see Cron setup below) for debugging.
4. Setting Up the Cron Job
To run this script automatically via system Cron:
- Find your PHP command-line path (run
which phpin terminal to get it) - Create a Cron entry (use
crontab -eto edit your Cron jobs) - Add a line like this (adjust paths to match your setup):
# Run every day at 2 AM 0 2 * * * /usr/bin/php /path/to/your/car-photo-importer.php >> /path/to/your/import-log.txt 2>&1- The
>> /path/to/import-log.txt 2>&1part saves all output (success/error messages) to a log file for later review.
- The
- Ensure the user running the Cron job has read/write permissions for the
car-photosandprocesseddirectories.
内容的提问来源于stack exchange,提问作者Daniel Iliaguev Harta
相关产品推荐
相关产品推荐

