Here's a concise summary of the solution:
The plugin creates an admin page that lists all directories in the wp-content/uploads/images/ directory. Each directory has an "Attach Images" button. When clicked, the plugin sends an AJAX request to attach all images in the directory to the product with a matching "source_title" meta field. The first image is set as the featured image, and subsequent images are added to the product gallery.
To use this plugin:
- Install and activate the plugin in WordPress.
- Navigate to the "Product Image Attach" page in the admin menu.
- Click the "Attach Images" button for the desired directory.
- The plugin will attach the images to the corresponding product.
<?php
/*
Plugin Name: Product Image Attach
Description: Attach images from directories to products based on directory name matching product's source_title meta field.
Version: 1.0
Author: Your Name
*/
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly
}
function list_directories($path) {
$directories = array();
$items = glob($path . '*', GLOB_ONLYDIR);
foreach ($items as $item) {
$directories[] = basename($item);
}
return $directories;
}
function product_image_attach_admin_page() {
add_menu_page(
'Product Image Attach',
'Product Image Attach',
'manage_options',
'product-image-attach',
'product_image_attach_page_content',
'dashicons-admin-media',
6
);
}
add_action('admin_menu', 'product_image_attach_admin_page');
function product_image_attach_page_content() {
if (!current_user_can('manage_options')) {
return;
}
$image_dir = WP_CONTENT_DIR . '/uploads/images/';
$directories = list_directories($image_dir);
echo '<div class="wrap">';
echo '<h1>Product Image Attach</h1>';
echo '<p>List of directories in the images directory:</p>';
echo '<ul>';
foreach ($directories as $directory) {
echo '<li>';
echo esc_html($directory);
echo ' <button class="button button-primary attach-images" data-directory="' . esc_attr($directory) . '">Attach Images</button>';
echo '</li>';
}
echo '</ul>';
echo '</div>';
// Add JavaScript for handling the AJAX request
echo '<script>
jQuery(document).ready(function($) {
$(".attach-images").click(function() {
var directory = $(this).data("directory");
var data = {
action: "attach_images",
directory: directory,
nonce: "' . wp_create_nonce('attach_images_nonce') . '"
};
$.post(ajaxurl, data, function(response) {
if (response.success) {
alert(response.data);
} else {
alert("Error: " + response.data);
}
});
});
});
</script>';
}
function attach_images() {
check_ajax_referer('attach_images_nonce', 'nonce');
if (!current_user_can('manage_options')) {
wp_send_json_error('Unauthorized', 403);
}
$directory = isset($_POST['directory']) ? sanitize_text_field($_POST['directory']) : '';
if (empty($directory)) {
wp_send_json_error('Directory name is required', 400);
}
$image_dir = WP_CONTENT_DIR . '/uploads/images/' . $directory . '/';
if (!file_exists($image_dir)) {
wp_send_json_error('Directory does not exist', 404);
}
$images = glob($image_dir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
if (empty($images)) {
wp_send_json_error('No images found in directory', 404);
}
// Find the product with the matching source_title
$args = array(
'post_type' => 'product',
'meta_key' => 'source_title',
'meta_value' => $directory,
'posts_per_page' => 1
);
$products = get_posts($args);
if (empty($products)) {
wp_send_json_error('No product found with source_title: ' . $directory, 404);
}
$product_id = $products[0]->ID;
$gallery_ids = array();
foreach ($images as $index => $image_path) {
// Check if file exists
if (!file_exists($image_path)) {
continue;
}
// Upload the image
$filetype = wp_check_filetype(basename($image_path), null);
if (!$filetype['type']) {
continue;
}
$attachment = array(
'guid' => $image_path,
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($image_path)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $image_path, $product_id);
if (is_wp_error($attach_id)) {
continue;
}
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attach_id, $image_path);
wp_update_attachment_metadata($attach_id, $attach_data);
// If it's the first image, set as featured image
if ($index === 0) {
set_post_thumbnail($product_id, $attach_id);
} else {
$gallery_ids[] = $attach_id;
}
}
// Update the product gallery if there are additional images
if (!empty($gallery_ids)) {
update_post_meta($product_id, '_product_image_gallery', implode(',', $gallery_ids));
}
wp_send_json_success('Images attached successfully');
}
add_action('wp_ajax_attach_images', 'attach_images');
function product_image_attach_enqueue_scripts() {
wp_enqueue_script('product-image-attach', plugin_dir_url(__FILE__) . 'js/product-image-attach.js', array('jquery'), '1.0', true);
wp_localize_script('product-image-attach', 'productImageAttach', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('attach_images_nonce')
));
}
add_action('admin_enqueue_scripts', 'product_image_attach_enqueue_scripts');