I’m working on a plugin, where part of functionality is image upload. I’ve managed to add actions and filters, which change upload destination folder, rename uploaded files, add two new sizes, and unsets default wordpress image sizes.
Now, everything works great here, but I have one really big issue:
All those settings remain active even when I upload image with help of WP Media Library.
I want those actions and filters to apply ONLY when user is using uploader on my plugin admin page. I want to avoid polluting web space with unnecesary image versions (and my plugin is going to use only sizes defined by me and original one) and I want to keep files in uploads subfolder created by my plugin, but only when user is uploading from plugin admin page.
In other words:
- If user uploads image from my plugin admin menu -> apply actions and filters.
- If user uploads image from standard wordpress Media menu page -> do not apply actions/filters.
I’ve tried to resolve my problem by using:
$screen = get_current_screen();
if ( in_array( $screen->id, array( 'my-admin-submenu-slug' ))) {
_code_goes_here_
}
But it failed miserably. Result was “false” in my uploader form input, so I guess slugs are not proper info to compare here or I’m missing something.
Is there any solution to this problem? I’ve spent last 3 days googling and trying to come up with solution, and nothing.
UPDATE
I’ve tried this:
if ($_REQUEST['page'] == 'bpc-add-products'){
echo '<p>Blebleblebleble</p>';
add_filter( 'image_make_intermediate_size', 'bpc_rename_prod_images' );
add_action( 'init', 'bpc_addimagesizes' );
add_filter( 'intermediate_image_sizes_advanced', 'bpc_filter_image_sizes' );
}
And the result: echo is printed only on bpc-add-products page – ok, that means my IF works. BUT filters and action are completely ignored.
I’ve also tried adding page suffix to hook names, like that:
add_filter( 'image_make_intermediate_size-my-plugin-name_page_bpc-add-products', 'bpc_rename_prod_images' );
And again nothing 🙁 I run out of ideas…
UPDATE #2
I have managed to solve upload directory part of my problem with help of two hooks:
add_filter('wp_handle_upload_prefilter', 'pre_upload_function', 2);
– used to add upload_dir filter connected with function which changes destination folder for uploaded files
add_filter('wp_handle_upload', 'post_upload_function', 2);
– used to remove upload_dir filter after upload, so when you use WordPress Media menu, your uploads will land in default folder
The following hook allows adding actions and filters on specified admin pages, it runs quite early on WP loading process:
To get the plugin hook: