I am in the process of a theme, I would like to add landing pages using page-templates. I cannot find anywhere that shows how to enqueue style or js for specific page templates. Any suggestions.
Ex. Landing Page 1 – landing-page-template-one.php will need very different style and js than the blog or homepage.
Leave a Reply
You must be logged in to post a comment.
If you plan to do a lot of WP development you should bookmark this page: http://codex.wordpress.org/Conditional_Tags
The other answer works but the conditional relies upon your page slug (myurl.com/this-is-the-slug) never changing. A more reliable method (IMO), and one that fits this case, would be to use the
is_page_template('example-template.php')
conditional check instead.You can use the
is_page( 'landing-page-template-one' )
conditional around your page specific styles / scripts as part of your over-all enqueue statements.You could even chain more
elseif
into the above for other pages, etc.Reference: Functions Reference –
is_page()
If the page template is located in a subdirectory of the theme (since WP 3.4), prepend the folder name and a slash to the template filename, e.g.:
So, whole function look like:
Reference: Official Documentations
I don’t know if the solutions provided in other answers used to work, but (since there’s no accepted answer!) it seems the correct answer is currently:
is_page_template() only works outside the loop, according to https://developer.wordpress.org/reference/functions/is_page_template/.
Say your template name is temper and you want to load bootstrap on that page so you can enqueue style on specific page templates like this:
go to function.php file then check the condition like this:
This one works perfectly.
Try this
In this example, the enqueue_my_script function is hooked to the wp_enqueue_scripts action, which is called by WordPress when it is loading scripts and stylesheets.
The function uses the is_page_template function to check if the current page is using a specific page template (in this case, ‘my-page-template.php’). If the condition is true, the wp_enqueue_script function is called to enqueue the ‘my-script’ script.
The wp_enqueue_script function takes the following arguments:
‘my-script’: This is the handle or identifier for the script. It should be unique and is used to reference the script when it is registered.
get_template_directory_uri() . ‘/js/my-script.js’: This is the URL of the JavaScript file.
array( ‘jquery’ ): This specifies that the script depends on the jquery script, which means that it should be loaded after the jquery script.
‘1.0’: This is the version number of the script.
true: This specifies that the script should be loaded in the footer of the HTML document.
You can use other conditional tags, such as is_home, is_front_page, is_single, and `