Здравствуйте!
Знакомый написал небольшой рнр скрипт, который при выборе файлов из библиотеки ВП и по нажатию кнопки "Создать архив" формирует архив zip и загружает в библиотеку. Можете под себя переделать его.
Дрбавить в functions.php
add_action("pre-plupload-upload-ui", "appendZipWrapper2UploadUI");
add_action("wp_ajax_createZIP", "createZipArchive");
add_action("wp_ajax_nopriv_createZIP", "createZipArchive");
function createZipArchive()
{
global $wpdb;
$wpdb->show_errors();
$isRemoveSrcNedded = true;
$postTable = $wpdb->get_blog_prefix()."posts";
$fileList = json_decode(preg_replace("#\\\\\"#", "\"", $_POST["fileList"]), true);
$parentPostID = get_posts
(
array
(
"post_type" => "attachment",
"include" => $fileList[0]
)
)[0]->post_parent;
$sqlQuery = "SELECT guid FROM ".$postTable." WHERE id IN (".implode(", ", $fileList).")";
$queryResult = $wpdb->get_results($sqlQuery);
$zipFileName =
"/tdoc".(new DateTime("", new DateTimeZone("Europe/Minsk")))->format("_Ymd_His").".zip";
$path2Archive = wp_upload_dir()["path"].$zipFileName;
$zip = new ZipArchive();
$zip->open($path2Archive, ZipArchive::CREATE);
foreach($queryResult as $row)
{
$path2File = $_SERVER["DOCUMENT_ROOT"].wp_make_link_relative($row->guid);
if(file_exists($path2File))
{
$zip->addFile($path2File, basename($path2File));
}
}
$result = $zip->close();
$filetype = wp_check_filetype(basename($path2Archive), null);
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($path2Archive),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename($path2Archive)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $path2Archive, $parentPostID);
$attach_data = wp_generate_attachment_metadata($attach_id, $path2Archive);
wp_update_attachment_metadata($attach_id, $attach_data);
if($isRemoveSrcNedded)
{
foreach($fileList as $currentAttacment)
{
wp_delete_attachment(intval($currentAttacment));
}
// file_put_contents(__DIR__."/item2del.txt", json_encode())
}
echo json_encode(["status" => $result, "filename" => basename($path2Archive)]);
die();
}
function appendZipWrapper2UploadUI()
{
// if(!current_user_can("upload_files")){return};
echo "
<style>
#waitImage
{
position: fixed;
left: calc(50% - 64px);
width: 128px;
height: 16px;
background-image: url(".get_template_directory_uri()."/images/waitImage.gif);
top: calc(50% - 7px);
z-index: 999999999999;
display: none;
}
</style>
<script>
var zipManagerWrapper = '<button ' +
'id=\"createZipBundle\" ' +
'style=\"margin-top:11px;margin-right:10px;width:100%;padding-left:2px;padding-right:2px;}\"' +
'class=\"button button-primary\">Архивировать</button>' +
'<div id=\"waitImage\"></div>',
captionWrapper = document.querySelectorAll('.media-frame .media-toolbar:nth-child(1) .media-toolbar-secondary'),
MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
contentObserver = new MutationObserver(function(mutations)
{
mutations.forEach(function(mutation)
{
if((mutation.type == 'childList') && (mutation.addedNodes.length != 0))
{
mutation.addedNodes.forEach(function(nodeItem)
{
if(nodeItem.childNodes)
{
nodeItem.childNodes.forEach(function(childItem)
{
if((childItem.nodeName == 'DIV') && (childItem.innerText.trim() == archiveName))
{
// console.log(nodeItem.dataset.id);
waitImage.style.display = 'none';
contentObserver.disconnect();
jQuery('li[data-id=\"' + nodeItem.dataset.id + '\"] .thumbnail').trigger('click');
}
});
}
});
}
});
}),
observerOption = {childList: true, characterData: true, subtree: true, attributes: true};
var waitImage,
archiveName;
if(captionWrapper.length == 1)
{
var isItemExists =
document.querySelectorAll('#createZipBundle').length == 0 ? false : true;
if(!isItemExists)
{
captionWrapper[0].innerHTML = zipManagerWrapper + captionWrapper[0].innerHTML;
waitImage = document.getElementById('waitImage');
jQuery('#createZipBundle').unbind();
jQuery('#createZipBundle').bind('click', createZipBundleHandle);
}
}
function createZipBundleHandle(event)
{
event.preventDefault();
var files2Zip = Array.prototype.filter.call
(
captionWrapper[0].parentElement.parentElement
.previousElementSibling.querySelectorAll('li'),
function(item)
{
return /selected/.test(item.classList.value);
}
).map
(
function(item)
{
return item.dataset.id;
}
);
console.log(JSON.stringify(files2Zip));
if(files2Zip.length > 0)
{
waitImage.style.display = 'block';
jQuery.ajax
({
url: ajaxurl,
method: 'POST',
data:
{
action: 'createZIP',
fileList: JSON.stringify(files2Zip)
},
success: function(data){console.log('Ответ от сервера');displayResult(data);},
error: function(error)
{
waitImage.style.display = 'none';
console.log('Что-то пошло не так');
console.log(error);
}
});
}
}
function displayResult(data)
{
var target = document.querySelectorAll('.media-modal.-select .media-modal-content .media-frame-content .attachments-browser ul')[0];
data = JSON.parse(data);
archiveName = data.filename;
contentObserver.observe(target, observerOption);
// jQuery('#media-attachment-date-filters').trigger('change')
wp.media.frame.state().get('library').props.set({ignore: (+ new Date())});
}
</script>";
}
В общем, нужно воспользоваться рнр.