web-dev-qa-db-ja.com

Wp_register_script()およびwp_register_style()の最適な場所

プラグインに複数のスクリプトとスタイルをエンキューする必要があります。しかし、wp_register_script()wp_register_style()を呼び出す必要があるたびにwp_enqueue_script()wp_enqueue_style()を呼び出すというアイデアは好きではありません。スクリプトとスタイルを一度登録してから、必要に応じてそれらを呼び出すことをお勧めします。

だから私の質問は、ワンタイム登録を有効にするためにwp_register_script()wp_register_style()を呼び出すためにアクションフックを使うことのベストプラクティスは何でしょうか?そして、どのアクションフックですか?

ありがとう。

1
Greeso

スクリプトとスタイルはwp_loadedフックに登録し、後でwp_enqueue_scriptsを使ってエンキューすることができます。

スクリプトとスタイルが登録されると、それらは元々登録されていたハンドルだけを使用して後でキューに入れることができます。

// Register scripts/styles. They can be optionally enqueued later on.
add_action( 'wp_loaded', 'wpse_register_scripts' );
function wpse_register_scripts() {
    wp_register_script( 'something-js', get_template_directory_uri() . '/js/something.js', array( 'jquery' ), true );
    wp_register_script( 'something-else-js', get_template_directory_uri() . '/js/something-else.js', array(), true );
    wp_register_script( 'another-something-else-js', get_template_directory_uri() . '/js/another-something-else.js', array(), true );
}

// Enqueue scripts/styles.
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_scripts' );
function wpse_enqueue_scripts() {
    // Load everywhere.
    wp_enqueue_script( 'something-js' );

    // Only enqueue scripts/styles on static front page.
    if ( is_front_page() ) {
        wp_enqueue_script( 'something-else-js' );
    }

    // Only enqueue scripts/styles when the full-width.php template is used.
    if ( is_page_template( 'full-width.php' ) ) {
        wp_enqueue_script( 'another-something-else-js' );
    }
}
2
Dave Romsey