Load jQuery từ CDN cho WordPress

Cập nhật lần cuối vào

jQuery là bộ code tích hợp mặc định trong nhân của WordPress, nếu giao diện hoặc plugin của bạn có sử dụng jQuery thì hệ thống sẽ lấy trực tiếp từ hosting bạn đang chạy. Nếu bạn nào muốn load jQuery theo kiểu lấy đường dẫn từ CDN thì làm như sau.

jQuery viết ít làm nhiều

Bạn mở tập tin functions.php của giao diện lên, hoặc bạn cũng có thể bỏ code này vào plugin của bạn. Sau đó bạn khai báo một hook như sau:

function hocwp_load_jquery_from_cdn() {
	global $wp_version, $wp_scripts;
	$handle   = ( version_compare( $wp_version, '3.6-alpha1', '>=' ) ) ? 'jquery-core' : 'jquery';
	$enqueued = wp_script_is( $handle );
	wp_enqueue_script( $handle );
	$version           = '';
	$jquery_url        = '';
	$google_not_exists = array(
		'1.12.3'
	);
	if ( is_a( $wp_scripts, 'WP_Scripts' ) ) {
		$registered = $wp_scripts->registered;
		if ( isset( $registered[ $handle ] ) ) {
			$version = $registered[ $handle ]->ver;
			if ( in_array( $version, $google_not_exists ) ) {
				$jquery_url = '//code.jquery.com/jquery-' . $version . '.min.js';
			}
		}
	}
	if ( empty( $version ) ) {
		$version = '1.12.0';
	}
	if ( empty( $jquery_url ) ) {
		$jquery_url = '//ajax.googleapis.com/ajax/libs/jquery/' . $version . '/jquery.min.js';
	}
	wp_dequeue_script( $handle );
	wp_deregister_script( $handle );
	wp_register_script( $handle, $jquery_url );
	if ( $enqueued ) {
		wp_enqueue_script( $handle );
	}
}
add_action( 'wp_enqueue_scripts', 'hocwp_load_jquery_from_cdn' );

Đoạn code bên trên sẽ lấy đường dẫn jQuery từ dịch vụ CDN của Google thay vì tải trực tiếp từ hosting của bạn. Để phòng tránh trường hợp code bị lỗi, đường dẫn không đúng và jQuery không được tải thì bạn thêm hàm bên dưới để kiểm tra.

function hocwp_jquery_google_cdn_fallback() {
	echo '<script>window.jQuery || document.write(\'<script src="' . includes_url( 'js/jquery/jquery.js' ) . '"><\/script>\')</script>' . "\n";
}

add_action( 'wp_footer', 'hocwp_jquery_google_cdn_fallback', 1 );

Chúc bạn thành công.