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

Last Updated: 2023년 07월 17일 | | 16개 댓글

워드프레스에서 자바스크립트(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);

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

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...)으로 둘러싸면 해당 조건을 충족하는 경우에만 로드됩니다.

참고:

References:


16 개 댓글

Leave a Comment

  1. 안녕하세요. 워드님,
    블로그에 유익한 글들이 많아 항상 많은 도움 얻어가고 있습니다.

    html, css에 대해서만 지식이 있다보니 워드프레스 페이지 작업 중 막히는 부분이 있어서 문의 드립니다.

    아래의 소스를 특정 페이지에 한해서만 적용하고 싶습니다.
    --------------------------------

    function sayHello(){
    alert("Hello World!")
    }

    클릭해주세요!

    --------------------------------
    일단 부분은 페이지에 적용했는데요.
    부분은 어떻게 처리해야하는지 알려주시면 감사하겠습니다.

    응답
  2. 좋은글 감사합니다.
    js 파일 적용 시, functions.php 최상단에 적용하지 않으니, 일부 Theme과 간섭이 일어나 White Blank Page 이슈가 일어나더라구요. 혹, 참고 될까하여 댓글 남겨봅니다. ㅎ

    응답
    • 안녕하세요?

      실행 순서와 관련되는 것 같네요.
      이 경우 priority를 지정하는 것이 바람직할 것 같습니다.

      add_action( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )

      응답
      • twentysixteen_datepicker > template-parts > functions.php

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

        //wp register script
        add_action( 'wp_enqueue_scripts', 'enqueue_and_register_my_scripts' );

        function enqueue_and_register_my_scripts(){
        //플러그인에서 로드하는 경우
        wp_register_script('test', plugin_dir_url(__FILE__) . 'datepicker.js', array('jquery'), '1.0', true);
        // jQuery(워드프레스에 의해 자동으로 등록)와 my-script(바로 위에서 등록됨)를 Dependency로 가지는 스크립트를 로드(Enquque)시킴
        wp_enqueue_script('test');

        //END

        twentysixteen_datepicker > template-parts > header.php

        twentysixteen_datepicker > js > datepicker.js

        $(function() {
        $( "#datepicker1" ).datepicker({
        dateFormat: 'yy-mm-dd'
        });
        });

        default_deadline > editor.php

        Date of Birth (DOB): <input type="text" id="kboard-input-option-deadline" name="kboard_option_deadline" value="option->deadline?>">

        default_deadline > document.php

        option->deadline?>

        이렇게 추가해보았는데요, 잘못된 부분이 있을까요?
        Parse error: syntax error, unexpected end of file in /host/home/super/html/wp-content/themes/twentysixteen_datepicker/functions.php on line 425

        이렇게 페이지가 떠서 처음부터 functions.php에서 안읽히네요 .. 어디서 설정을 잘못한건지..
        425줄은 참고로 맨 마지막 줄이에요
        kboard timepicker 페이지 소스 한번 받을 수 있을까요?

      • 안녕하세요?

        함수 파일에서는 위의 코드를 다 삭제하고 아래 코드만 추가해보시기 바랍니다.

        function wpdocs_scripts_method() {
        wp_register_script('datepicker-scripts', get_stylesheet_directory_uri() . 'js/datepicker.js', array('jquery'), '1.0', true);
        wp_enqueue_script('datepicker-scripts');

        }
        add_action( 'wp_enqueue_scripts', 'wpdocs_scripts_method' );

        date picker에 대해서는 다른 글에서 자세히 설명했으니 그대로 따라하면 별 문제가 없을 것입니다.