محدودیت برای آپلود تصویر در ووکامرس
این کد تعداد تصاویر قابل افزودن به گالری محصولات ووکامرس را به حداکثر ۳ تصویر محدود میکند.
هنگام انتخاب تصاویر، تعداد تصاویر موجود در گالری بررسی میشود و اگر مجموع تصاویر بیشتر از ۳ عدد باشد، تصاویر اضافی انتخاب نمیشوند و پیام هشدار به کاربر نمایش داده میشود.
این محدودیت فقط در بخش ویرایش محصولات ووکامرس اعمال میشود و روی سایر بخشهای وردپرس تأثیری ندارد.
<?php
add_action('admin_footer', function () {
global $post_type;
if ($post_type !== 'product') {
return;
}
?>
<script>
jQuery(function($){
const maxImages = 3;
function getCurrentCount() {
return $('#product_images_container ul.product_images li.image').length;
}
$(document).on('click', '.add_product_images', function(){
setTimeout(function(){
if (typeof wp === 'undefined' || !wp.media || !wp.media.frame) {
return;
}
let frame = wp.media.frame;
if (!frame) {
return;
}
frame.off('select.galleryLimit');
frame.on('select.galleryLimit', function(){
let selection = frame.state().get('selection');
let selectedCount = selection.length;
let currentCount = getCurrentCount();
if ((currentCount + selectedCount) > maxImages) {
alert(
'حداکثر ۳ تصویر برای گالری مجاز است.\n' +
'اکنون ' + currentCount + ' تصویر در گالری وجود دارد.'
);
let allowed = maxImages - currentCount;
selection.each(function(attachment, index){
if(index >= allowed){
selection.remove(attachment);
}
});
return false;
}
});
frame.state().get('selection').on('add remove reset', function(){
let selection = frame.state().get('selection');
let currentCount = getCurrentCount();
if ((selection.length + currentCount) > maxImages) {
let last = selection.last();
if (last) {
selection.remove(last);
}
alert(
'بیش از ۳ تصویر نمیتوانید انتخاب کنید.'
);
}
});
}, 300);
});
});
</script>
<?php
});