The best way to do this would be to add a Meta Box to the Add / Edit Page dashboard.
Then, when enqueueing scripts, you can check the metadata for that post, and if it’s set, enqueue the script.
NOTE: there’s a lot of moving pieces here. I’ll try to break it down into digestable chunks.
Sample code. Note – you would need to insert into functions.php, and tweak to your specific theme:
First, let’s get the metabox registered to show up
function slider_script_add_meta_box() {
add_meta_box(
'do_script_sectionid',
'Include Slider Script',
'slider_script_meta_box',
'page'
);
}
add_action( 'add_meta_boxes', 'slider_script_add_meta_box' );
Now, let’s display the metabox option
function slider_script_meta_box( $post ) {
// Add an nonce field so we can check for it later.
wp_nonce_field( 'slider_script_action_name', 'slider_script_meta_box_nonce' );
// Get existing value if set
$value = get_post_meta( $post->ID, '_do_slider_script', true );
$checked = ($value) ? ' checked' : '';
echo '<label for="myplugin_new_field">';
echo 'Include Slider Script:';
echo '</label> ';
echo '<input type="checkbox" id="do_slider_script" name="do_slider_script"' . $checked . ' />';
}
Next, hook the page save to ensure the data gets saved
function myplugin_save_meta_box_data( $post_id ) {
// Check if our nonce is set and verifies.
if ( ! isset( $_POST['slider_script_meta_box_nonce'] ) || ! wp_verify_nonce( $_POST['slider_script_meta_box_nonce'], 'slider_script_action_name' ) ) {
return;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user's permissions.
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return;
}
}
// Finally! Safe for us to save the data now.
// Sanitize user input.
$do_script = (isset($_POST['do_slider_script'])) ? 1 : 0;
// Update the meta field in the database.
update_post_meta( $post_id, '_do_slider_script', $do_script );
}
add_action( 'save_post', 'myplugin_save_meta_box_data' );
FINALLY, add this section to actually register / enqueue your script on the relevant pages
function enqueue_slider_scripts() {
global $post;
$do_script = get_post_meta($post->ID, '_do_slider_script', true);
if ($do_script) {
// Alter the path to your script as needed
wp_enqueue_script('slider_script', get_template_directory_uri() . '/js/example.js');
}
}
add_action( 'wp_enqueue_scripts', 'enqueue_slider_scripts' );
Again, all of these can be pasted into your functions.php file. Alternatively, a more organized way would be to create a new php file in your theme folder, and include it into the functions file. This would allow you to give the file a meaningful name, and keep the code “organized” into related groups.