Gỡ tất cả CSS và JS của WooCommerce ở những trang không phải Cửa Hàng

Nếu bạn muốn gỡ tất cả CSS và JS của WooCommerce ở những trang không phải Cửa Hàng, bài viết này sẽ giúp bạn.

Gỡ tất cả CSS và JS của WooCommerce ở những trang không phải Cửa Hàng

Thêm đoạn mã sau vào functions.php. Đoạn mã này đã được thử nghiệm với WordPress 6.6.1WooCommerce 9.1.4.

/**
 * Kiểm tra trang WooCommerce
 */
function is_wc_page(): bool {
	return class_exists('WooCommerce') && (
		is_woocommerce() || is_cart() || is_checkout() || is_account_page()
	);
}

/**
 * Gỡ bỏ asset và hook của WooCommerce nếu không phải trang Woo
 */
function disable_woocommerce_assets() {
	if ( is_wc_page() ) {
		return;
	}

	// Gỡ generator tag
	remove_filter('get_the_generator_html', 'wc_generator_tag', 10);
	remove_filter('get_the_generator_xhtml', 'wc_generator_tag', 10);

	// Gỡ scripts của Woo
	remove_action('wp_enqueue_scripts', [WC_Frontend_Scripts::class, 'load_scripts']);
	remove_action('wp_print_scripts', [WC_Frontend_Scripts::class, 'localize_printed_scripts'], 5);
	remove_action('wp_print_footer_scripts', [WC_Frontend_Scripts::class, 'localize_printed_scripts'], 5);

	// Gỡ phần gallery fallback nếu JS tắt
	remove_action('wp_head', 'wc_gallery_noscript');

	// Gỡ body class WooCommerce
	remove_filter('body_class', 'wc_body_class');
}
add_action('template_redirect', 'disable_woocommerce_assets');

/**
 * Gỡ bỏ style của WooCommerce nếu không cần
 */
function filter_woocommerce_styles($enqueue_styles): array {
	return is_wc_page() ? $enqueue_styles : [];
}
add_filter('woocommerce_enqueue_styles', 'filter_woocommerce_styles');

/**
 * Gỡ style nội tuyến của Woo nếu không cần
 */
function dequeue_woocommerce_inline_styles() {
	if ( ! is_wc_page() ) {
		wp_dequeue_style('woocommerce-inline');
	}
}
add_action('wp_enqueue_scripts', 'dequeue_woocommerce_inline_styles', 100);

Chúc các bạn thành công!

Bình Luận


  • Không có bình luận.