워드프레스에서 js 스크립트 파일과 스타일시트를 올바르게 로드하는 방법

 

워드프레스에서 자바스크립트(js) 파일이나 스타일시트 파일(css)을 로드하려면 wp_enqueue_script() 함수를 사용합니다. 이 글에서는 다양한 상황에서 js/css 파일을 워드프레스에 로드하는 방법에 대해 살펴보겠습니다.

워드프레스에서 js 스크립트 파일과 스타일시트를 올바르게 로드하기

wp_enqueue_script

wp_enqueue_script ( string $handle, string|bool $src = false, array $deps = array(), string|bool $ver = false, bool $in_footer = false )

파라미터:

  • $handle
    (string) (필수) 스크립트 이름
  • $src
    (string|bool) (옵션) 워드프레스 루트 디렉터리로부터 스크립트의 경로. 예: '/js/myscript.js'.
    기본값: false
  • $deps
    (array) (옵션) 이 스크립트가 의존하고 있는 등록된 핸들의 array.
    기본값: array()
  • $ver
    (string|bool) (옵션) 스크립트 버전 번호. 이 파라미터는 캐싱에 상관 없이 올바른 버전이 클라이언트에 전달되도록 하는 데 사용됩니다.
    기본값: false
  • $in_footer
    (bool) (옵션) 스크립트가 </head> 앞에 위치할지 아니면 </body> 앞에 위치할지를 지정합니다. 기본값은 'false'입니다. 'false' 또는 'true' 사용 가능.
    기본값: false

예시:

다음과 같은 코드를 함수 파일에 추가하도록 합니다.

function wpdocs_scripts_method() {
wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom_script.js', array( 'jquery' ) );
}
add_action( 'wp_enqueue_scripts', 'wpdocs_scripts_method' );

위에서 get_stylesheet_directory_uri()는 자식 테마가 있는 경우 자식 테마의 경로를 가리킵니다. 만약 부모 테마의 경로를 가리키려면 get_template_directory_uri()를 사용하도록 합니다. 따라서 위의 액션 함수는 테마 폴더 아래의 js/custom_script.js 파일을 후크(enqueue)하게 됩니다.

wp register script

wp register script는 워드프레스 내의 스크립트 파일을 등록했다가 wp_enqueue_script() 함수를 사용하여 페이지에 연결하는 데 사용되며 스크립트 의존성(Dependency)를 안전하게 처리합니다.

사용법:

wp_register_script( $handle, $src, $deps, $ver, $in_footer );

예시:

add_action( 'wp_enqueue_scripts', 'enqueue_and_register_my_scripts' );

function enqueue_and_register_my_scripts(){
wp_register_script( 'my-script', get_stylesheet_directory_uri() . '/js/my-script.js' ); // 테마 폴더 내 js 폴더 아래의 my-script.js 파일을 등록
// jQuery(워드프레스에 의해 자동으로 등록)와 my-script(바로 위에서 등록됨)를 Dependency로 가지는 스크립트를 로드(Enquque)시킴
wp_enqueue_script( 'my-careers-script', get_stylesheet_directory_uri() . '/js/my-careers-script.js', array( 'jquery', 'my-script' ) );
}

플러그인에서 로드하는 경우에는

wp_register_script('test', plugin_dir_url(__FILE__) . 'test.js', array('jquery'), '1.0', true);

위와 같이 스크립트를 등록한 후에

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

wp_enqueue_script('test');

위와 같은 방식으로 스크립트를 include시킵니다. plugin_dir_url( __FILE__ )은 플러그인 _FILE_의 경로를 나타냅니다. 따라서 위의 경우 해당 플러그인 폴더 아래의 test.js 파일을 로드하게 됩니다.

function myplugin_scripts() {
wp_register_style( 'foo-styles',  plugin_dir_url( __FILE__ ) . 'assets/foo-styles.css' );
wp_enqueue_style( 'foo-styles' );
}
add_action( 'wp_enqueue_scripts', 'myplugin_scripts' );

플러그인 폴더 아래의 CSS를 로드할 경우 위와 같은 형태로 사용할 수 있습니다. 다음과 같은 코드로 사용자 CSS를 로드할 수 있습니다.

function custom_style_sheet() {
wp_enqueue_style( 'custom-styling', get_stylesheet_directory_uri() . '/mycustom.css' );
}
add_action('wp_enqueue_scripts', 'custom_style_sheet');

특정 페이지에 스크립트 로드하기

특정 페이지나 특정 조건을 지정하여 스크립트를 로드(후크)시킬 수 있습니다.

function enqueue_and_register_my_scripts(){

wp_register_script( 'my-script', get_stylesheet_directory_uri() . '/js/my-script.js' );

// Enqueues a script only to be used on a specific page of the site
// 사이트의 특정 페이지에만 사용하도록 스크립트를 enquque(후크)시킴
if ( is_page( 'careers' ) ){

wp_enqueue_script( 'my-careers-script', get_stylesheet_directory_uri() . '/js/my-careers-script.js', array( 'jquery', 'my-script' ) );
}
}

위와 같이 wp_enqueue_script() 부분을 조건문(if...)으로 둘러싸면 해당 조건을 충족하는 경우에만 로드됩니다.

[출처] https://www.thewordcracker.com/intermediate/how-to-load-js-files-in-wordpress/

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
403 Webassembly Tutorial using Emscripten file 졸리운_곰 2020.10.24 646
402 [웹어셈블리] Visual Studio 2019와 Emscripten (emcc) 개발 file 졸리운_곰 2020.10.18 2094
401 [속깊은 자바스크립트 강좌] 자바스크립트의 Scope와 Closure 기초 file 졸리운_곰 2020.09.16 447
400 [Javascript] with 명령에 대하여 졸리운_곰 2020.09.16 459
399 HTML DIV tag - 테두리 그리기 STYLE - BORDER 졸리운_곰 2020.08.26 241
398 CSS :: 버튼(Button) 예쁘게 꾸미기, 여러개의 버튼 그룹화 하기 file 졸리운_곰 2020.08.26 994
397 [button] CSS - Button - 버튼스타일 (버튼크기, 버튼색깔, 버튼비활성화, 버튼그룹, 이미지위버튼) 졸리운_곰 2020.08.26 2293
396 워드프레스 데이터베이스 들여다보기. file 졸리운_곰 2020.08.04 672
395 제로보드 XE의 최근 게시글 5개를 DB에서 직접 조회 졸리운_곰 2020.08.04 456
394 GUI 디자이너를 위한 색상 참고 사이트 file 졸리운_곰 2020.08.04 609
393 Webpack 완전정복하기!! file 졸리운_곰 2020.07.20 726
392 [javascript] 압축(Minify) / 난독화(Uglify) 졸리운_곰 2020.07.01 292
391 HTML div 왼쪽, 오른쪽 배치 졸리운_곰 2020.06.02 470
390 [html] iframe을 사용하지 말아야 할 이유. (단점) 졸리운_곰 2020.05.10 567
389 워드프레스 플러그인과 테마 비교 - 사이트별 플러그인 만들기 졸리운_곰 2020.04.21 501
» 워드프레스에서 js 스크립트 파일과 스타일시트를 올바르게 로드하는 방법 졸리운_곰 2020.04.21 735
387 워드프레스 플러그인 만들기 file 졸리운_곰 2020.04.21 499
386 워드프레스 숏코드: 완벽 가이드 file 졸리운_곰 2020.04.21 513
385 생산성을 빠르게 높여주는, 프런트엔드 개발 툴 10가지 file 졸리운_곰 2020.04.10 488
384 자바스크립트 자료구조 연결 리스트(Linked List) file 졸리운_곰 2020.03.30 324
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED