0

I wanted to include some javascript and css files on only some of my WordPress pages. To do this, I registered and enqueued the files in my child theme's functions.php file, and used conditionals to select my target pages. For example, to include a javascript file only in a page called "publications", I used this:

define('child_template_directory', dirname( get_bloginfo('stylesheet_url')) );

function add_my_js() {
if (is_page('publications')) {
wp_register_script('my_js_script',child_template_directory.'/js/my_js_script.js');
wp_enqueue_script('my_js_script');
}
}
add_action('wp_enqueue_scripts', 'add_my_js');

I added a number of these in my child theme's functions.php file, some being javascript files (using wp_enqueue_script), and some being css files (using wp_enqueue_style).

There may be more than one page where I wanted to place the files (say, on an "essays" page as well as on "publications"), so I thought maybe I could do something like:

if ( (is_page('publications')) || (is_page('essays')) ) {
//[etc]
}

But, as well as the possibility of there being many of them, I may now also be in the situation where the target pages may vary from time to time, so I'm wondering how to cater for this.

I thought of keeping the names of the pages (like "publications" and "essays" above) which would have to go into the conditional, in a database table, then, via a query, placing them into an array ('publications','essays'), and then perhaps using something like in_array() in place of the if conditional - or maybe a switch() statement.

Basically I'm wondering (1) what's the best way to write the query first, and (2) how to place the array elements into what sort of conditional (or switch, or whatever), inside the functions.

Hope this all makes sense.

2
  • Getting your array to work with a conditional is basically a PHP question, not a WordPress one, and how you should save your data is a bit of broad question but you could look up custom meta and the Options API. – s_ha_dum Nov 17 '13 at 21:53
  • Well I achieved half of what I wanted by retrieving my array of pages from the database, then, in the function, getting the current slug and looking to see if it was in the array retrieved. But in my own back-end admin I'm still left with needing to place, into an array, every slug of every post, of all post types, even custom post types (excluding attachments). Anyone know how to do this? I don't see that this as a PHP question, since such a function must be specific to WordPress. – John Doe Nov 19 '13 at 12:36

Your Answer

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

Browse other questions tagged or ask your own question.