4

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.

2

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 :)

  • This work around appears to have worked thanks... hopefully they fix it soon. Plugins should definitely be sandboxed in my opinion. – Goodbytes Jun 9 '15 at 10:18
  • 1
    If you don't know the hook of your plugin page (it is different to the page slug), then you can use the get_plugin_page_hook() function. – shea Jun 16 '15 at 9:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.