I have developed a WordPress plugin for my site that utilises the WP Media uploader to store files… To do this my plugin contains the following code:
function enqueue_scripts()
{
wp_enqueue_script('jquery');
wp_enqueue_media();
// etc...
}
add_action('admin_enqueue_scripts', 'enqueue_scripts');
I noticed the admin area was becoming really slow so I ran some query logs and it appears the query triggered by wp_enqueue_media();
SELECT ID
FROM wp_posts
WHERE post_type="attachment"
AND post_mime_type LIKE 'audio%'
LIMIT 1
After a quick Google search I can see it is a known problem on large sites that was apparently fixed many versions previous…. obviously not!
I’m not quite sure how to proceed? I need this functionality in my plugin. I am a little confused why this function needs calling when it appears to generally be available throughout the admin area.. Even stranger, when i’m loading things from my enqueue_scripts() function they are being made available globally, which I’m assuming is what is happening to wp_enqueue_media() as it is slowing the whole admin area and not just the plugin.
I presumed it would only load resources when it needed them.
Is there a way around it? or is there a way to only trigger enqueue_scripts() when I am using the plugin?
I just don’t get why I need to load these from the plugin, but then it’s made globally to all other plugins.
1 Answer
To load admin scripts only on your pages, you should use the $hook
-parameter:
function enqueue_scripts( $hook )
{
if( 'my-page' != $hook )
return;
wp_enqueue_script('jquery');
wp_enqueue_media();
// etc...
}
add_action('admin_enqueue_scripts', 'enqueue_scripts');
Concerning the loading problem. This seems to be still an open problem. The ticket 27985 was followed up by #32264, which is not closed yet. The last edit on this was 24hours ago 🙂
Seems like they are searching for a solution and will implement it soon 🙂