نمایش و ایمپورت عکسهای قالب در گالری وردپرس
این کد امکان ایمپورت تصاویر موجود در پوشه image قالب فرزند را به کتابخانه رسانه وردپرس فراهم میکند.
امکانات اصلی:
اضافه شدن دکمه «افزودن تصاویر جدید» به صفحه رسانه وردپرس.
بررسی پوشه hello-child/image برای پیدا کردن تصاویر.
پشتیبانی از فرمتهای JPG، JPEG، PNG، GIF، WebP، SVG، BMP و TIFF.
اضافه کردن تصاویر به کتابخانه رسانه بدون نیاز به آپلود دستی.
جلوگیری از ایجاد تصاویر تکراری.
نمایش تعداد تصاویر جدید اضافهشده و فایلهای تکراری یا دارای خطا.
بروزرسانی خودکار صفحه رسانه پس از ایمپورت موفق.
حفظ آدرس اصلی تصاویر موجود در پوشه قالب.
تشخیص ابعاد تصاویر و ثبت اطلاعات آنها در متادیتای وردپرس.
محدود کردن قابلیت ایمپورت به کاربرانی که دسترسی مدیریت سایت دارند.
استفاده از AJAX برای انجام عملیات بدون بارگذاری مجدد صفحه.
برای استفاده، تصاویر موردنظر را داخل پوشه image قالب فرزند قرار دهید و سپس از مسیر رسانه ← کتابخانه روی دکمه «افزودن تصاویر جدید» کلیک کنید.
<?php
add_action('admin_footer-upload.php', 'add_import_theme_images_button');
function add_import_theme_images_button() {
if (!current_user_can('manage_options')) return;
$screen = get_current_screen();
if ($screen->id !== 'upload') return;
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
var container = document.createElement('div');
container.style.cssText = 'margin:10px 0 10px auto;padding:10px 15px;background:#f6f7f7;border:1px solid #dcdcde;border-radius:6px;max-width:600px;display:flex;align-items:center;gap:10px;flex-wrap:wrap;direction:rtl;text-align:right;';
container.innerHTML = `
<span style="font-size:13px;color:#50575e;">
📁 <code style="background:#e8e8e8;padding:1px 5px;border-radius:3px;font-size:12px;">hello-child/image</code>
</span>
<button id="import-theme-images-btn" class="button button-small" style="font-size:12px;">
🔄 افزودن تصاویر جدید
</button>
<span id="import-status" style="font-size:12px;font-weight:bold;"></span>
`;
var wrap = document.querySelector('.wrap');
if (wrap) wrap.insertBefore(container, wrap.firstChild);
document.getElementById('import-theme-images-btn').addEventListener('click', importThemeImages);
});
function importThemeImages() {
var btn = document.getElementById('import-theme-images-btn');
var status = document.getElementById('import-status');
btn.disabled = true;
btn.textContent = '⏳ ...';
status.textContent = '';
fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: 'action=import_theme_images&nonce=<?php echo wp_create_nonce("import_theme_images_nonce"); ?>'
})
.then(res => res.json())
.then(data => {
btn.disabled = false;
btn.textContent = '🔄 افزودن تصاویر جدید';
if (data.success) {
status.style.color = '#46b450';
status.textContent = '✅ ' + data.data.message;
setTimeout(() => location.reload(), 1500);
} else {
status.style.color = '#dc3232';
status.textContent = '❌ ' + data.data.message;
}
}).catch(() => {
btn.disabled = false;
btn.textContent = '🔄 افزودن تصاویر جدید';
status.style.color = '#dc3232';
status.textContent = '❌ خطا';
});
}
</script>
<?php
}
add_filter('wp_get_attachment_url', 'fix_attachment_url', 10, 2);
function fix_attachment_url($url, $post_id) {
if (strpos($url, '/wp-content/themes/hello-child/image/') !== false) {
$clean_url = home_url('/wp-content/themes/hello-child/image/' . basename($url));
return $clean_url;
}
return $url;
}
add_action('wp_ajax_import_theme_images', 'handle_import_theme_images');
function handle_import_theme_images() {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'دسترسی غیرمجاز']);
}
check_ajax_referer('import_theme_images_nonce', 'nonce');
$theme_path = get_stylesheet_directory() . '/image';
$theme_url = get_stylesheet_directory_uri() . '/image';
if (!is_dir($theme_path)) {
wp_send_json_error(['message' => 'پوشه image پیدا نشد.']);
}
$allowed_ext = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'tiff'];
$files = glob($theme_path . '/*');
if (!$files) {
wp_send_json_error(['message' => 'هیچ فایلی در پوشه پیدا نشد.']);
}
global $wpdb;
$new = 0;
$skipped = 0;
$errors = 0;
foreach ($files as $file_path) {
if (!is_file($file_path)) continue;
$filename = basename($file_path);
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (!in_array($ext, $allowed_ext)) {
continue;
}
$file_url = $theme_url . '/' . $filename;
$slug = sanitize_title(pathinfo($filename, PATHINFO_FILENAME));
$existing = $wpdb->get_var($wpdb->prepare(
"SELECT ID FROM {$wpdb->posts} WHERE post_name = %s AND post_type = 'attachment'",
$slug
));
if ($existing) {
$skipped++;
continue;
}
$filetype = wp_check_filetype($filename, null);
if (!$filetype['type']) {
if ($ext === 'svg') $filetype['type'] = 'image/svg+xml';
else continue;
}
$img = @getimagesize($file_path);
$width = 0;
$height = 0;
if ($ext === 'svg') {
$svg_content = file_get_contents($file_path);
if (preg_match('/viewBox="[^"]* (\d+) (\d+)"/', $svg_content, $matches)) {
$width = $matches[1];
$height = $matches[2];
} elseif (preg_match('/width="(\d+)" height="(\d+)"/', $svg_content, $matches)) {
$width = $matches[1];
$height = $matches[2];
} else {
$width = 100;
$height = 100;
}
} else {
$width = $img ? $img[0] : 0;
$height = $img ? $img[1] : 0;
}
$wpdb->insert($wpdb->posts, array(
'post_author' => get_current_user_id(),
'post_date' => current_time('mysql'),
'post_date_gmt' => current_time('mysql', 1),
'post_title' => pathinfo($filename, PATHINFO_FILENAME),
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => $filetype['type'],
'guid' => $file_url,
'post_name' => $slug
));
$attach_id = $wpdb->insert_id;
if ($attach_id) {
$wpdb->insert($wpdb->postmeta, array(
'post_id' => $attach_id,
'meta_key' => '_wp_attached_file',
'meta_value' => $file_url
));
$metadata = array(
'width' => $width,
'height' => $height,
'file' => $file_url,
'sizes' => array()
);
$wpdb->insert($wpdb->postmeta, array(
'post_id' => $attach_id,
'meta_key' => '_wp_attachment_metadata',
'meta_value' => serialize($metadata)
));
$new++;
} else {
$errors++;
}
}
$msg = "✅ {$new} تصویر جدید اضافه شد.";
if ($skipped > 0) $msg .= " ({$skipped} تکراری)";
if ($errors > 0) $msg .= " ({$errors} خطا)";
wp_send_json_success([
'message' => $msg,
'new_count' => $new
]);
}