I need your help. I've programmed a custom cron function within WordPress, which uses the WooCommerce product importer class to automatically import products:
$update_importer = WC_Product_CSV_Importer_Controller::get_importer( $import_result, [
'delimiter' => ',',
'start_pos' => 0,
'mapping' => $mapping_columns,
'update_existing' => true,
'lines' => apply_filters( 'woocommerce_product_import_batch_size', 30 ),
'parse' => true
] );
$update_results = $update_importer->import();
$update_percent_complete = $update_importer->get_percent_complete();
Everything works quite nice, instead of the categories. The categories are getting parsed & imported during the import via the admin panel, but not via the cron job.
So I've started digging into WooCommerce and found out, that there is a check within the parsing function during the WooCommerce product import which does a capability check:
// Don't allow users without capabilities to create new categories.
if ( ! current_user_can( 'manage_product_terms' ) ) {
break;
}
Since the cron job gets executed as user 0, the check fails and no categories are getting imported.
My idea was now to just set the admin user manually before the import and reset it to 0 again after the import finished:
wp_set_current_user( 1 );
$update_importer = WC_Product_CSV_Importer_Controller::get_importer( $import_result, [
'delimiter' => ',',
'start_pos' => 0,
'mapping' => $mapping_columns,
'update_existing' => true,
'lines' => apply_filters( 'woocommerce_product_import_batch_size', 30 ),
'parse' => true
] );
$update_results = $update_importer->import();
$update_percent_complete = $update_importer->get_percent_complete();
wp_set_current_user( 0 );
This seems to work, but I'm worried if this opens a door for hackers because when a guest or someone else e.g. a customer visits the site, all crons are normally executed within WordPress in case they are overdue.
I'm not really sure if the process runs in a different thread... As far as I know, PHP can not even do multithreading, so no idea!
I'm glad for any advice/help I can get. Thanks
CodePudding user response:
How about assigning the capability to the '0' User instead of logingin the admin ( Mostly user ID 1 will be an admin user ) while importing and removing the capability after the import is done.
add_action('set_current_user', 'custom_set_current_user');
function custom_set_current_user() {
global $current_user;
if (0 == $current_user->ID) {
// add $cap capability to this user
$current_user->add_cap('manage_product_terms');
}
}
The user object will be like - After the import is finished, remove the capability.
// remove $cap capability from this user
$current_user->remove_cap('manage_product_terms');