Změna adresáře pro nahrávání médií

Jeden z mých klientů importoval tisíce produktů za pomoci pluginu WP All Import.

Vše fungovalo výborně, ale problém byl s obrázky – všechny se nahrávaly do jedné složky, a protože WordPress generuje pro každý obrázek několik rozměrů, v jedné složce bylo více než 100 000 tisíc souborů, což samozřejmě způsobilo problémy s rychlostí a serverem.

Řešením bylo použít filtr upload_dir, pomocí kterého se dá dynamicky měnit cesta k nahrávaným souborům.

Výsledný plugin vypadal takto:

[php]
<?php
/*
Plugin Name: WPAI – Fix images
Plugin URI: http://IHaveNoIdeaWhereThisCodeWillBeUsed.com
Description: Activate this plugin to have max 500 images in a directory when importing images with WP All Import
Author: Václav Greif
Version: 1.0
Author URI: https://wp-programator.cz/
Textdomain: wpaiif
*/

/**
* Change upload path for WP All Import
*
* We are using upload_dir filter to change the upload params
* There doesn’t seem a way to add the filter only for WPAI (I tried to hook this to ‚pmxi_before_xml_import‘, but that
* didn’work at all
*
* That means, when doing import, be sure to activate the plugin
*/
add_filter(‚upload_dir‘, ‚wpaiif_upload_dir‘);
function wpaiif_upload_dir($param ) {

$last_dir_no = get_option(‚wpaiif_last_dir_no‘,1);
$import_dir = ‚wpai‘;

$param[‚path‘] = $param[‚basedir‘].’/‘ . $import_dir . ‚/‘. $last_dir_no;
$param[‚url‘] = $param[‚baseurl‘].’/‘ . $import_dir . ‚/‘. $last_dir_no;
$param[‚subdir‘] = ‚/‘. $import_dir . ‚/‘. $last_dir_no;

// This is here just to create the first directory
if (!file_exists($param[‚path‘])) {
mkdir($param[‚path‘], 0777, true);
}

// Count files in directory
$files_count = wpaiif_count_files($param[‚path‘]);

if ($files_count < 400) {
// If less than X files in directory, return $params
return $param;
} else {
// If more than X files in directory, just increasethe wpaiif_last_dir_no option

$last_dir_no++;
update_option(‚wpaiif_last_dir_no‘,$last_dir_no);

$param[‚path‘] = $param[‚basedir‘].’/‘ . $import_dir . ‚/‘. $last_dir_no;
$param[‚url‘] = $param[‚baseurl‘].’/‘ . $import_dir . ‚/‘. $last_dir_no;
$param[‚subdir‘] = ‚/‘. $import_dir . ‚/‘. $last_dir_no;

// Be sure the directory exists
if (!file_exists($param[‚path‘])) {
mkdir($param[‚path‘], 0777, true);
}
}

// Whoopeee, we are done
return $param;

}

/**
* Count files in directory
* Regarding http://stackoverflow.com/questions/12801370/count-how-many-files-in-directory-php this is the fastet method
* @param $dir
* @return int
*/
function wpaiif_count_files ($dir)
{
$f = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
return iterator_count($f);
}
[/php]

Přidat komentář