WordPress – Loading scripts only on specific pages or posts

WordPress load script on specific page only
WordPress load script on specific page only

So you want your WordPress to load a script on specific pages, thus being more efficient and clean – great!

Maybe you already know about enqueuing files like JavaScript or CSS already, but you are searching for a way to optimize.

As I just stumbled upon this problem myself today (and in the past), I thought I need to share this.

While I’ve done my usual research, I just noticed that there aren’t that many, nor good examples online.

I was totally surprised, that this commonly faced task isn’t that widespread across the WordPress developer community.

Even though I found some lonely examples, I had to find out, that those didn’t work at least for my WordPress situation.

So i just continued looking for more and was kinda disappointed..

Some code was just clearly outdated and there also was some code, which didn’t feel really clean.

It doesn’t feel good stacking code into the „functions.php„, messing it up more and more.

I think one of the most common sources for this to work on are custom plugins.

You should (if you don’t have already) make your own plugin, which is responsible for handling those occasionally needed files.

I mean it could also tackle topics regarding the eventually existing shortcodes or custom page types.

Those could be the ones actually needing your stylesheets and client sided, manipulating JavaScript code.

Keep in mind though, that I won’t dive into building your own WordPress plugin in this post that deep.

This would be some kind of separated topic for another one of my blog posts!

Why you should consider loading scripts only for specific pages

Why should WordPress load script only specific pages
Why should WordPress load script only specific pages

So after we had this brief introduction, let’s dive a bit deeper into the developer aspect of loading „assets“.

Those assets can be different files like the normal styling thingys, for example „Cascading Style Sheets“ or in short CSS.

They will enhance your visual user experience by beautifying your user interface.

Whether it’s about making those shiny glossy buttons, to make your user wanna click that thing.

Or like aligning your content the right way with like the flexbox layout – oh gawd, thank you for having that.

One other common asset-ish file would be the clientside script language file type called JavaScript.

It will help you generating dynamic HTML on the client side, or sending like AJAX requests to a server.

But as always: Most things having an upside, will mostly come at some kind of cost or a downside.

In the next step, we will talk about the common downsides of those nice helper files.

The thing they all share in common – using up space, taking time

So even after generating that nice HTML output by for example PHP and styling it appropriately using CSS – theres one thing.

Those nice helper files will need webspace, just like every other downloadable file.

They have to be downloaded by the users browser and will mostly consume one request per file.

Each one of those requests will consume some time, even though if they are fast, right!?

So we will have to consider saving each one of those not really necessary requests.

This will not only make our users happier by saving some data – especially if you are on a mobile network.

It will also increase the loading time in general, making the user reaching it goal the fastest way possible.

Google and other search engines will also love you for caring about your users considering that.

I’m sure there are a lot of persons who could actually improve their general SEO by speeding up their site like this.

Commonly used methods to tackle that

A typical case for caching

The first and I think the most well-known mechanism is actually the caching functionality of most browsers.

Not every page visit will trigger downloading the same assets over and over again.

Common assets, especially images, styles and JavaScript files will be managed by your browser.

For sure this is one of the great possibilities to help the client visiting your websites (and like search engine bots).

But even if this is one nice available helper, this won’t help at the very root of our problem.

Let’s talk about that in a second..

Minification for more help

Another on commonly used method to tackle that problem is called „minification„.

It will basically remove any unneeded character from the output to make it even more compact.

Some tools are even able to optimize the output by renaming like variables, functions, etc.

This way the tools help us by saving even more speed, storage and bandwith.

Surely this is actually nice, as it can already make a great impact on the results, but this isn’t like the top solution.

Like this, we only work on the ending side, instead of focusing on the root of the problem.

The real approach – loading scripts only on specific pages

WordPress only load necessary scripts on specific pages
WordPress only load necessary scripts on specific pages

So now we have come to the final point, meaning what you should possibly actually do.

Avoiding those unnecessary requests by just loading those files you actually need.

In my case I had this nice, selfmade plugin, which was loading some JavaScript and CSS files into the page.

At first, it generated the needed HTML structure and appended all these shiny classes to the correct elements.

Then it would obviously rely on the correct scripts being loaded for those pages.

But the problem was: I noticed that those scripts were loaded on literally every post on my site.

Even more problems – errors

Next to those already discussed problems like space, speed, requests, etc. there was one more problem.

I was just busy doing some other stuff on one of the blog posts, when I noticed errors in the console.

A JavaScript file was looking for different HTML elements ready to get manipulated by the script, but wait a second!

The elements weren’t there, because they would only be generated by some shortcode which wasn’t used on that post.

Even if i think that most search engine crawlers and users browsers will ignore console errors.

Don’t pin me down on this, but I think this counts for at least non critical or ground breaking errors.

Still it doesn’t feel right like that, I mean the page won’t be rendered correctly.

Enqueuing Scripts – right before our optimization

Before we go ahead and actually work on a better solution, let’s see how we could’ve done it before.

Basically it’s done by hooking our plugin into the „wp_enqueue_scripts“-action and doing some additional stuff.

That additional stuff is actually calling those additional functions depending on our needs:

So one basic example code could look similar to this:

function vendor_pluginabbreviation_load_assets()
  $plugin_url = plugin_dir_url(__FILE__);
  wp_enqueue_style('pluginabbreviation-style', $plugin_url . 'css/style.css');
  wp_enqueue_script('pluginabbreviation-script', $plugin_url . 'js/script.js', [], '', true);
add_action('wp_enqueue_scripts', 'vendor_pluginabbreviation_load_assets');

Let’s optimize – only loading scripts for specific pages

Now let’s actually optmize this code from above, to only load scripts, when we are on a specific page/on specific pages.

To do so, we need find out, which pages or posts we are actually targeting, so let’s do this.

Go into your WordPress backend and check the page or post id by looking at the parameter provided in the URL:.

Please don’t get confused by my german WordPress installation, as it will still look similar in other languages.

Finding out the post & page ids of desire

You can just use your mouse to hover over the corresponding blog post and spot the post id in the URL display at the very bottom.

The same way will also work for finding out page ids, just go topages“ and do the same.

Keep in mind, that the parameter will still be called „post id„, even though it is actually a page.

Checking for being a post and matching ids

In the next step we should take care about actually checking for those ids and requiring them to be in our favor.

For sure you can proceed how you would like to, but in my case, it looks like this.

I want those scripts and styles only to be added, if it’s one of the specified ids, so I created meaningful variables for those ids.

$englishConverterPostId = 7275;
$germanConverterPostId = 7194;

Then it should already work, if the WordPress „is_page“-function is returning true for our ids.

You can also pass page slugs, ids, or even a mix consisting of both possibilities to this function as well.

$isConverterPost = is_page([ $englishConverterPostId, $germanConverterPostId ]);

Sadly I had to find out that it didn’t work for my case, even though it’s the most recommended approach.

So I did some debugging by checking, if the „is_page“-function existed at this time, first:

print_r([ 'isPageExists' => function_exists('is_page'), ]);

That actually resulted into the output of a true-ish value, meaning the function existed – okay.

Next I confirmed the page ids being the right ones, but I still couldn’t make it work, the function still returned false.

I didn’t know and I still don’t know what I was/am doing wrong, so I just made it work another way.

So I just created access to the global post„-variable and checked the id on that one:

global $post;
$englishConverterPostId = 7275;
$germanConverterPostId = 7194;
$isConverterPost = $post->ID === $germanConverterPostId || $post->ID === $englishConverterPostId;

Finally I could continue by checking that „isConverterPost„-variable to register the scripts depending on that:

if ($isConverterPost) {
  $plugin_url = plugin_dir_url(__FILE__);
  wp_enqueue_style('dcc-style', $plugin_url . 'css/style.css');
  wp_enqueue_script('dcc-script', $plugin_url . 'js/script.js', [], '', true);

At the very end, the final script looked like this:

function rr_dcc_load_plugin_assets()
  global $post;
  $englishConverterPostId = 7275;
  $germanConverterPostId = 7194;

  $isConverterPost = $post->ID === $germanConverterPostId || $post->ID === $englishConverterPostId;
  if ($isConverterPost) {
    $plugin_url = plugin_dir_url(__FILE__);
    wp_enqueue_style('dcc-style', $plugin_url . 'css/style.css');
    wp_enqueue_script('dcc-script', $plugin_url . 'js/script.js', [], '', true);
add_action('wp_enqueue_scripts', 'rr_dcc_load_plugin_assets');

If you need a fully working, easy to use example, then just go ahead and download the example files below.


WordPress load script on specific page – Conclusion
WordPress load script on specific page – Conclusion

So at the end of this little post we talked about loading assets and a good way of doing so.

As loading assets will consume like requests, time & data file by file, we should avoid loading unnecessary ones.

We can help by using a mechanism called „minification„, but this will still conquer a general rule of thumb:

Just avoid what you don’t need, or in our case – don’t load those unused asset files!

Finally, we implemented a functionality by using the well-known WordPress function called „is_page„.

This way, we would only load needed JavaScript & CSS files on the actual needed pages.


Here you will find an easy to install and quick to use example.

Just download the zip folder, unzip it and upload the containing folder to your WordPress plugins folder.

After that (or even before) you need to adjust the page/post ids to the ones you desire.

Then you can activate this example plugin in your WordPress backend and visit the configured areas.

The script file and the stylesheets should only be loaded on the specified posts/pages.

Then visit another non configured page id and see that it’s not loaded there.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht.