Xóa một script /stylesheet bạn gọi hàm wp_dequeue_script, wp_dequeue_style. Ví dụ sau tôi sẽ không sử dụng thư viện jquery-ui mặc định của wordpress.
/**
* Dequeue the jQuery UI script.
*
* Hooked to the wp_print_scripts action, with a late priority (100),
* so that it is after the script was enqueued.
*/
function wpdocs_dequeue_script() {
wp_dequeue_script( 'jquery-ui-core' );
}
add_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 );
|
Ví dụ khác bạn sẽ muốn thay thế jquery trong wordpress, sử dụng link jquery ngoài:
function my_init() {
if (!is_admin()) {
// comment out the next two lines to load the local copy of jQuery
wp_deregister_script('jquery');
wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js', false, '1.3.2');
//wp_enqueue_script('jquery');
}
}
add_action('init', 'my_init');
|
Lưu ý: sử dụng hook tương tự trong lúc chèn script/styles, và cũng để xóa file scripts/styles ra khỏi website.
- Theme Support:
Viền mầu đỏ được tạo bởi add_theme_support('custom-background'); và sử dụng hook 'wp_print_styles'. Để xóa nó đi bạn gán lại vào hook này:
# Deregister style file
function deregister_styles() {
wp_deregister_style( 'style' );
# Remove Custom Background
remove_theme_support( 'custom-background');
}
add_action( 'wp_print_styles', 'deregister_styles', 100 );
add_action('wp_enqueue_scripts', 'deregister_styles', 100); #this hook for enqueue style handle.
|
- Thay thế file khác:
Hủy đăng ký script/style cũ và thay thế bởi một file khác:
# Deregister scripts file
function remove_default_scripts () {
wp_deregister_script('foundation');
//you also want to replace new one
wp_enqueue_script( 'foundation', get_stylesheet_directory_uri() . '/javascripts/swanchika.js', array('jquery'), '1.0', true );
}
add_action( 'wp_print_scripts', 'remove_default_scripts', 100 );
add_action('wp_enqueue_scripts', 'remove_default_scripts', 0);
|
- Defer tag:
Hook 'script_loader_tag' cho phép bạn sửa thuộc tính thẻ script, hỗ trợ từ wordpress phiên bản 4.1.0
// script_loader_tag hook added in WP 4.1
add_filter( 'script_loader_tag', 'script_loader_tag1',10, 3);
function script_loader_tag1( $tag, $handle ,$src) {
if( is_admin() ) {
return $tag;
}
return str_replace( ' src', ' defer="defer" src', $tag );
}
|
Chú ý: Để site load nhanh hơn, thẻ script nên khai báo thuộc tính 'defer', như thế này:
<script src="demo_defer.js" defer></script>
Ngoài ra bạn có thể làm điều này với hook 'clean_url'. Ví dụ sau thêm thuộc tính 'async' vào thẻ script.
if (!(is_admin() )) {
function defer_parsing_of_js ( $url ) {#_print( $url);
if ( FALSE === strpos( $url, '.js' ) ) return $url;
if ( strpos( $url, 'jquery.js' ) !=false) return $url;
return "$url' async onload=' ";
}
add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 );
}
|
Kết quả: <script src="..." async onload=''
Trường hợp thêm đầy đủ thuộc tính defer sẽ là:
return "$url' defer='defer";
|
Unregistered version