I am working on a template that my coworkers will be using to populate content. On some of the pages there will be a slider or multiple sliders but on other pages there won’t be any. Because of this, I would like to create an option(maybe a checkbox or something) in the Pages backend that will allow them to include the slider script if necessary.

I could enqueue the script only on specific page IDs, but since they will be creating many of these pages, I would rather have an automated way for them to include the Javascript themselves instead of me having to go in and add more page IDs every time they make a new page which uses the Javascript.

Additionally I would like to use only 1 page template if possible.

What would be the best way to go about this?

Thanks!

1 Answer
1

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.

Leave a Reply

Your email address will not be published. Required fields are marked *