我在我的functions.php文件中使用wp_enqueue_script()为前端用户提供了使用dropzone.js上传图像的功能。它使我的方面非常缓慢,我得到这个错误:
wp_enqueue_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks.
这是有问题的代码,它工作得很好,完全符合我的要求,但会让我的网站变慢。我在这里做错了什么?
wp_enqueue_script('dropzone','wp-content/themes/storefront/assets/js/dropzone.js', array('jquery'));
wp_enqueue_script('my-script','wp-content/themes/storefront/footer.php', array('jquery','dropzone'));
$drop_param = array(
'upload'=>admin_url( 'admin-ajax.php?action=handle_dropped_media' ),
'delete'=>admin_url( 'admin-ajax.php?action=handle_delete_media' ),
);
wp_localize_script('my-script','dropParam', $drop_param);
add_action( 'wp_ajax_handle_dropped_media', 'BMP_handle_dropped_media' );
add_action( 'wp_ajax_nopriv_handle_dropped_media', 'BMP_handle_dropped_media' );
function BMP_handle_dropped_media() {
// status_header(200);
$upload_dir = wp_upload_dir();
$upload_path = $upload_dir['path'] . DIRECTORY_SEPARATOR;
$num_files = count($_FILES['file']['tmp_name']);
$post_id = get_the_ID();
$newupload = 0;
if ( !empty($_FILES) ) {
$files = $_FILES;
foreach($files as $file) {
$newfile = array (
'name' => $file['name'],
'type' => $file['type'],
'tmp_name' => $file['tmp_name'],
'error' => $file['error'],
'size' => $file['size']
);
$_FILES = array('upload'=>$newfile);
foreach($_FILES as $file => $array) {
$newupload = my_handle_attachment( $file, $post_id );
}
}
}
echo $newupload;
die();
}
add_action( 'wp_ajax_handle_delete_media', 'BMP_handle_delete_media' );
add_action( 'wp_ajax_nopriv_handle_delete_media', 'BMP_handle_delete_media' );
function BMP_handle_delete_media(){
if( isset($_REQUEST['media_id']) ){
$post_id = absint( $_REQUEST['media_id'] );
$status = wp_delete_attachment($post_id, true);
if( $status )
echo json_encode(array('status' => 'OK'));
else
echo json_encode(array('status' => 'FAILED'));
}
die();
}
感谢您的帮助。 这是我从原来提取代码的地方。 How to integrate Dropzonejs with wordpress media handler in frontend?
答案 0 :(得分:1)
将wp_enqueue_script()调用包含在函数中:
function your_styles_scripts() {
wp_enqueue_script('dropzone','wp-content/themes/storefront/assets/js/dropzone.js', array('jquery'));
wp_enqueue_script('my-script','wp-content/themes/storefront/footer.php', array('jquery','dropzone'));
$drop_param = array(
'upload'=>admin_url( 'admin-ajax.php?action=handle_dropped_media' ),
'delete'=>admin_url( 'admin-ajax.php?action=handle_delete_media' ),
);
wp_localize_script('my-script','dropParam', $drop_param);
}
相关的操作挂钩,根据您的用例需要:
add_action( 'admin_enqueue_scripts', 'your_styles_scripts' );
或
add_action( 'wp_enqueue_scripts', 'your_styles_scripts' );