最好的方法是添加Meta Box 添加/编辑页面仪表板。
然后,在将脚本排队时,可以检查该帖子的元数据,如果设置了元数据,则将脚本排队。
注意:这里有很多活动部件。我会把它分解成可消化的小块。
示例代码。注意-您需要在函数中插入。php,并根据您的特定主题进行调整:
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, 所有这些都可以粘贴到函数中。php文件。或者,一种更有条理的方法是在主题文件夹中创建一个新的php文件,并将其包含到函数文件中。这将允许您为文件指定一个有意义的名称,并将代码“组织”到相关的组中。