WordPress Plugin for Attaching Product Images from Directories
Here's a complete plugin that will:
- List all directories in the
wp-content/uploads/images/ folder
- Allow you to attach images from each directory to products with matching
source_title meta
Plugin Files
1. Main Plugin File (product-image-attacher.php)
<?php
/*
Plugin Name: Product Image Attacher
Description: Attach product images from directories based on source_title meta
Version: 1.0
Author: Your Name
*/
defined('ABSPATH') or die('Direct access not allowed');
class ProductImageAttacher {
public function __construct() {
add_action('admin_menu', array($this, 'add_admin_page'));
add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
add_action('wp_ajax_attach_product_images', array($this, 'handle_ajax_request'));
}
public function add_admin_page() {
add_submenu_page(
'woocommerce',
'Product Image Attacher',
'Image Attacher',
'manage_options',
'product-image-attacher',
array($this, 'render_admin_page')
);
}
public function enqueue_scripts($hook) {
if ($hook !== 'woocommerce_page_product-image-attacher') {
return;
}
wp_enqueue_style(
'product-image-attacher-css',
plugin_dir_url(__FILE__) . 'assets/css/style.css'
);
wp_enqueue_script(
'product-image-attacher-js',
plugin_dir_url(__FILE__) . 'assets/js/script.js',
array('jquery'),
'1.0',
true
);
wp_localize_script(
'product-image-attacher-js',
'productImageAttacher',
array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('product_image_attacher_nonce')
)
);
}
public function render_admin_page() {
$upload_dir = wp_upload_dir();
$base_dir = trailingslashit($upload_dir['basedir']) . 'images/';
if (!file_exists($base_dir)) {
echo '<div class="wrap"><h1>Product Image Attacher</h1>';
echo '<div class="notice notice-error"><p>The images directory does not exist: ' . esc_html($base_dir) . '</p></div>';
echo '</div>';
return;
}
$directories = array_filter(glob($base_dir . '*'), 'is_dir');
echo '<div class="wrap"><h1>Product Image Attacher</h1>';
echo '<div class="notice notice-info"><p>This tool will attach images from directories to products with matching source_title meta.</p></div>';
if (empty($directories)) {
echo '<div class="notice notice-warning"><p>No directories found in: ' . esc_html($base_dir) . '</p></div>';
echo '</div>';
return;
}
echo '<table class="wp-list-table widefat fixed striped">';
echo '<thead><tr><th>Directory</th><th>Product Match</th><th>Images Found</th><th>Action</th></tr></thead>';
echo '<tbody>';
foreach ($directories as $dir) {
$dir_name = basename($dir);
$product = $this->find_product_by_source_title($dir_name);
$images = $this->count_images_in_directory($dir);
echo '<tr>';
echo '<td>' . esc_html($dir_name) . '</td>';
echo '<td>' . ($product ? esc_html($product->get_name()) . ' (ID: ' . $product->get_id() . ')' : 'No matching product') . '</td>';
echo '<td>' . esc_html($images) . '</td>';
echo '<td>';
if ($product && $images > 0) {
echo '<button class="button button-primary attach-images" data-dir="' . esc_attr($dir_name) . '">Attach Images</button>';
echo '<span class="spinner"></span>';
echo '<div class="result-message"></div>';
} else {
echo 'No action available';
}
echo '</td>';
echo '</tr>';
}
echo '</tbody></table>';
echo '</div>';
}
public function handle_ajax_request() {
check_ajax_referer('product_image_attacher_nonce', 'nonce');
if (!current_user_can('manage_options')) {
wp_send_json_error('Unauthorized', 403);
}
$dir_name = sanitize_text_field($_POST['dir']);
$result = $this->attach_images_from_directory($dir_name);
wp_send_json_success($result);
}
private function find_product_by_source_title($source_title) {
$products = wc_get_products(array(
'meta_key' => 'source_title',
'meta_value' => $source_title,
'limit' => 1
));
return !empty($products) ? $products[0] : false;
}
private function count_images_in_directory($dir) {
$images = glob($dir . '/*.{jpg,jpeg,png,gif,webp}', GLOB_BRACE);
return count($images);
}
private function attach_images_from_directory($dir_name) {
$upload_dir = wp_upload_dir();
$dir_path = trailingslashit($upload_dir['basedir']) . 'images/' . $dir_name . '/';
$image_files = glob($dir_path . '*.{jpg,jpeg,png,gif,webp}', GLOB_BRACE);
if (empty($image_files)) {
return array(
'success' => false,
'message' => 'No images found in directory'
);
}
$product = $this->find_product_by_source_title($dir_name);
if (!$product) {
return array(
'success' => false,
'message' => 'No product found with source_title: ' . $dir_name
);
}
$gallery_ids = array();
$results = array();
foreach ($image_files as $index => $image_path) {
$filename = basename($image_path);
$file_info = pathinfo($filename);
// Check if image already exists in media library
$existing_attachment = $this->find_existing_attachment($filename, $dir_name);
if ($existing_attachment) {
$attachment_id = $existing_attachment->ID;
$results[] = 'Using existing attachment for: ' . $filename;
} else {
// Prepare attachment data
$filetype = wp_check_filetype($filename, null);
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => sanitize_file_name($file_info['filename']),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert attachment
$attachment_id = wp_insert_attachment($attachment, $image_path);
if (is_wp_error($attachment_id)) {
$results[] = 'Failed to insert attachment for: ' . $filename . ' - ' . $attachment_id->get_error_message();
continue;
}
// Generate attachment metadata
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata($attachment_id, $image_path);
wp_update_attachment_metadata($attachment_id, $attachment_data);
$results[] = 'Created new attachment for: ' . $filename;
}
// Add to product
if ($index === 0) {
// First image - set as featured image
$product->set_image_id($attachment_id);
$results[] = 'Set as featured image: ' . $filename;
} else {
// Additional images - add to gallery
$gallery_ids[] = $attachment_id;
$results[] = 'Added to gallery: ' . $filename;
}
}
if (!empty($gallery_ids)) {
$product->set_gallery_image_ids($gallery_ids);
}
$product->save();
return array(
'success' => true,
'message' => 'Successfully attached images for: ' . $dir_name,
'details' => $results
);
}
private function find_existing_attachment($filename, $dir_name) {
$upload_dir = wp_upload_dir();
$relative_path = 'images/' . $dir_name . '/' . $filename;
$attachments = get_posts(array(
'post_type' => 'attachment',
'posts_per_page' => 1,
'post_status' => 'inherit',
'meta_query' => array(
array(
'key' => '_wp_attached_file',
'value' => $relative_path,
'compare' => 'LIKE'
)
)
));
return !empty($attachments) ? $attachments[0] : false;
}
}
new ProductImageAttacher();