I’m trying to figure out how to enqueue files (javascript and styles) based on a condition- is_page() from within my plugin’s config file. For a week now, I’ve been trying to find a working solution out of the myriads I’ve found online.
Here’s the original from the file:
public function enqueue_files() {
wp_enqueue_script("jquery");
wp_enqueue_style("wpsqt-main",plugins_url('/css/main.css',WPSQT_FILE));
}
Here’s what I attempted:
public function enqueue_files() {
if ( is_page(xxx) ) {
wp_enqueue_script("jquery");
wp_enqueue_style("wpsqt-main",plugins_url('/css/main.css',WPSQT_FILE));
}
}
When I test if ( is_page() )
, it removes the scripts and styles from the headers of all pages. However, when altering it to:
if ( !is_page() )
, it adds it back. Weird?
- Is there a way to do include the condition?
- Does the public function portion alter the way the condition is read?
- Is it possible to remove the enqueue from the plugin’s config file and place it in my function.php file so whenever the plugin is updated, I don’t have to make changes?
Here’s the file (the call to enqueue the file is at the very bottom): http://pastebin.com/sDt4sTCH
I included the actual file so you can get the context it’s used in. Thanks in advance!!
EDIT better code format
You’re calling is_page() too early, before there has been a query, so no $post is available to test with. And if (not is_page()) will always be true in this case. The way I circumvent this is to insert the scripts into the footer as opposed to the header (after there has been a query). Note, you need to have
<?php wp_footer() ?>
in your website footer, usually before</body>
Alternatively, you can use a global variable and simply set it to true wherever you want your script printed. For instance, if you don’t know the page name. Simply replace the print_my_scripts method above with this one.
And add this to any shortcode, widget, page template.. anything to tell our script to print on the page using the shortcode, widget, template.. and so on.