Implementation to use Excel export as a bulk action in the WordPress backend. To use with the Wefabric themosis implementation. It uses the https://github.com/SpartnerNL/Laravel-Excel (v3.0) package.
- Wefabric WP Support
- Themosis
Run the following command
composer require wefabric/wp-excelPublish the config file
php console vendor:publish --tag=wp-excelEvery post type needs to be registered for export before usage. In the following example we will register the export class for a default WordPress post
- First you need to create the class which converts the posts data to an Illuminate Collection. To do this run the following command
php console make:export PostsExport- Add the logic to export the WordPress posts to the Illuminate collection for example:
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Wefabric\WPExcel\Concerns\WpPostsExcellable;
class PostsExport implements FromCollection, WithHeadings, WpPostsExcellable
{
protected array $postIds = [];
public function headings(): array
{
return [
'Id',
'Title',
];
}
/**
* @return \Illuminate\Support\Collection
*/
public function collection(): Collection
{
$args = [
'post_type' => 'post',
'posts_per_page' => -1,
];
if($this->postIds) {
$args['post__in'] = $this->postIds;
}
$posts = get_posts($args);
$collection = new Collection();
foreach ($posts as $post) {
$collection->push([
'Id' => $post->ID,
'Title' => $post->post_title,
]);
}
return $collection;
}
public function setPostIds(array $postIds)
{
$this->postIds = $postIds;
}
}- Add the class to the wp-excel config file (config/wp-excel.php). Where 'post' is the post type name and the second parameter is the export class
return [
'post_types' => [
'post' => \App\Exports\PostsExport::class,
]
]- Go to the WordPress backend (wp-admin/edit.php), select a post and run the bulk action.
The default export format is 'XLSX'. To use a different export format change the 'default_format' in the wp-excel config file (config/wp-excel.php) to the correct format. The allowed export formats are located here: https://docs.laravel-excel.com/3.0/exports/export-formats.html