Skip to content

Instantly share code, notes, and snippets.

@eto4detak
Created March 1, 2019 10:00
Show Gist options
  • Save eto4detak/34e5dd640b98b516bdac182379a02ae8 to your computer and use it in GitHub Desktop.
Save eto4detak/34e5dd640b98b516bdac182379a02ae8 to your computer and use it in GitHub Desktop.
wp php xls excel
<?php
/////// ADMIN PAGE SETTINGS AND IMPORT EXPORT
class Divie_Import_Export_XLS
{
function __construct()
{
add_action('admin_menu', [$this, 'divie_register_page_import_product']);
if (wp_doing_ajax()) {
add_action('wp_ajax_divie_import_site_product', [$this, 'divie_import_site_product']);
}
}
static function divie_arr_to_xls($sheet,$arr = [])
{
$index_loop = 2;
foreach ($arr as $key => $product) {
$sheet->setCellValue('A'.$index_loop, $product[0]);
$sheet->setCellValue('B'.$index_loop, $product[1]);
$sheet->setCellValue('C'.$index_loop, $product[2]);
$sheet->setCellValue('D'.$index_loop, $product[3]);
$index_loop++;
}
return $sheet;
}
// получить все продукты
static function divie_get_all_products($value='')
{
$products = [];
$args = array(
'post_type' => array( 'product',),
'post_status' => array( //(string / array) - use post status. Retrieves posts by Post Status, default value i'publish'.
'publish', // - a published post or page.
'pending', // - post is pending review.
'draft', // - a post in draft status.
'auto-draft', // - a newly created post, with no content.
'future', // - a post to publish in the future.
'private', // - not visible to users who are not logged in.
'inherit', // - a revision. see get_children.
'trash' // - post is in trashbin (available with Version 2.9).
),
// 'paged' => get_query_var( 'paged' ),
'posts_per_page' => -1,
);
$the_query = new WP_Query( $args );
// The Loop
global $post;
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) :
$the_query->the_post();
$wc_product = new WC_Product( $post->ID );
$product = [];
$product[] = $wc_product->get_sku() ? $wc_product->get_sku() : '';
$product[] = $wc_product->get_title() ? $wc_product->get_title() : '';
$product[] = $wc_product->get_price() ? $wc_product->get_price() : '';
$product[] = get_post_meta($post->ID, '_euro_rate', true) ? get_post_meta($post->ID, '_euro_rate', true) : '';
$products[] = $product;
endwhile;
endif;
return $products;
}
static function divie_add_file_export_xls($value='')
{
require_once get_template_directory() . '/inc/PhpSpreadsheet/vendor/autoload.php';
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'артикул');
$sheet->setCellValue('B1', 'наименование товара');
$sheet->setCellValue('C1', 'цена в рублях');
$sheet->setCellValue('D1', 'цена в евро');
$arr = self::divie_get_all_products();
$seheet = self::divie_arr_to_xls($sheet, $arr);
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xls($spreadsheet);
$path = wp_upload_dir()['basedir'] .'/import_product_excel';
$url = wp_upload_dir()['baseurl'] .'/import_product_excel';
// add dir
wp_mkdir_p($path);
// save file
$file_name = 'vipklinker_ru_'.date('y-m-d-H-i-s').'.xls';
$file_path = $path.'/'.$file_name;
$file_url = $url.'/'.$file_name;
$writer->save($file_path);
return $file_url;
}
static function divie_file_import_xls($value='')
{
$path = $_FILES['my_image_upload']['tmp_name'];
require_once get_template_directory() . '/inc/PhpSpreadsheet/vendor/autoload.php';
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
$reader->setReadDataOnly(TRUE);
$spreadsheet = $reader->load($path);
$worksheet = $spreadsheet->getActiveSheet();
echo '<table>' . PHP_EOL;
foreach ($worksheet->getRowIterator() as $row) {
echo '<tr>' . PHP_EOL;
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(FALSE);
$index = 0;
$product_info = [];
foreach ($cellIterator as $cell) {
$product_info[] = $cell->getValue();
$index++;
}
if(!empty($product_info[0])){
$id = wc_get_product_id_by_sku($product_info[0]);
if(!empty($id)){
$wc_product = new WC_Product( $id);
$price = get_post_meta($id, '_price', true) ? get_post_meta($id, '_price', true) : '';
$sale_price = get_post_meta($id, '_sale_price', true) ? get_post_meta($id, '_sale_price', true) : '';
$new_product_name = $product_info[1] ? $product_info[1] : '';
$new_price = floatval(str_replace(",", ".", $product_info[2]));
$new_euro_price = floatval(str_replace(",", ".", $product_info[3]));
if(!empty($new_price)){
if(!empty($sale_price)){
update_post_meta($id, '_sale_price', $new_price);
update_post_meta($id, '_price', $new_price );
}else{
update_post_meta($id, '_regular_price', $new_price);
update_post_meta($id, '_price', $new_price );
}
}
if(!empty($new_euro_price)){
update_post_meta($id, '_euro_rate', $new_euro_price);
}
if(!empty($new_product_name)){
$my_post = array();
$my_post['ID'] = $id;
$my_post['post_title'] = $new_product_name;
wp_update_post( wp_slash($my_post) );
}
}
}
echo '</tr>' . PHP_EOL;
}
echo '</table>' . PHP_EOL;
return true;
}
static function divie_register_page_import_product()
{
$page_hook = add_submenu_page('edit.php?post_type=product', 'Импорт экспорт товаров xls файла', 'Импорт экспорт товаров xls файла', 'manage_options', 'register-page-import-product', [$this, 'divie_calback_import_product']);
// добавляем контекст при загрузке страницы
add_action( "load-{$page_hook}", [$this, 'divie_admin_product_import_utl'] );
}
static function divie_admin_product_import_utl($value='')
{
add_action('admin_enqueue_scripts', [$this, 'divie_ajax_data_divieimportnonce']);
}
static function divie_calback_import_product()
{
$html = '';
if(isset( $_POST['my_image_upload_nonce'] ) ){
if (
wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
&& current_user_can( 'manage_options')
) {
$finish = self::divie_file_import_xls();
if ( is_wp_error( $finish ) ) {
$html = "Ошибка обновление";
} else {
$html = "Все обновлено";
}
} else {
$html = "<div>Проверка не пройдена. Товары не обновлены</div>";
}
}
echo '<div class="wrap"><h3 class="edit-attributes__description">Импорт экспорт товаров</h3>';
echo "<div><button id='divie-export-products'>Экспартировать все товары</button></div>";
?>
<br/><br/><br/>
<p class="divie-p">Импортировать товары из xls файла</p>
<form id="divie_upload" method="post" action="#" enctype="multipart/form-data">
<input type="file" name="my_image_upload" accept=".xls" id="my_image_upload" multiple="false" />
<?php wp_nonce_field( "my_image_upload", "my_image_upload_nonce" ); ?>
<input id="submit_my_image_upload" name="submit_my_image_upload" type="submit" value="Начать импорт" />
</form>
<?php
echo $html;
?>
</div>
<script type='text/javascript'>
(function($) {
jQuery('#divie-export-products').on("click", function(e) {
eto_start_import();
});
function eto_start_import() {
var data = {
action: 'divie_import_site_product',
dataType: 'json',
nonce_code : divieimportnonce.nonce
};
jQuery.post( divieimportnonce.url, data, function(response) {
window.location.href = response.data;
});
}
})(jQuery);
</script>
<?php
}
static function divie_ajax_data_divieimportnonce()
{
wp_localize_script('jquery', 'divieimportnonce',
array(
'url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('divieimport-nonce'),
)
);
}
static function divie_import_site_product()
{
if (!wp_verify_nonce($_POST['nonce_code'], 'divieimport-nonce')) {
die('Stop!');
}
$file_name = self::divie_add_file_export_xls();
wp_send_json_success($file_name);
wp_die();
}
}
$import_export_xls = new Divie_Import_Export_XLS();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment