1

ここで単純なものが間違いなく欠けているように感じます...しかし、私の人生では、欠けているものを見つけることができません。

私は、jQuery 関数を header.php ファイルに直接含めるという「悪い習慣」を持っています (他の場所の中でも特に)。私が理解しているように、これは嫌われており、関数は wp_enqueue 関数を使用して別のファイルに保存してロードする必要があります(正しく取得した場合)。

私はここにある解決策に従おうとしています: WordPress に簡単な jQuery スクリプトを追加するにはどうすればよいですか?

私の header.php には、ドキュメントの準備ができたときに起動するこの単純な関数があります。

<script>
    // Scroll to Top
    jQuery(document).ready(function () {
        // Force element to hidden state when page loads
        jQuery('.scroll-to-top').hide();

        // Check to see if the window is top if not then display button
        jQuery(window).scroll(function () {
            if (jQuery(this).scrollTop() > 200) {
                jQuery('.scroll-to-top').fadeIn();
            } else {
                jQuery('.scroll-to-top').fadeOut();
            }
        });
        //Click event to scroll to top
        jQuery('.scroll-to-top').click(function () {
            jQuery('html, body').animate({ scrollTop: 0 }, 800);
            return false;
        });
    });
</script>

そこで、「正しく」実行するために、コードを取り出して myScripts.js に配置しました (もちろんスクリプト タグは削除しています)。functions.php ファイルに、次のコードを追加しました。

<?php
    function add_my_script() {
        wp_enqueue_script(
            'myScripts', // name your script so that you can attach other scripts and de-register, etc.
            get_template_directory_uri() . '/js/myScripts.js', // this is the location of your script file
            array('jquery') // this array lists the scripts upon which your script depends
        );
    }

    add_action( 'wp_enqueue_scripts', 'add_my_script' );
?>

しかし、ページを読み込むと、スクリプトが機能しなくなります。

編集

これまでの助けに感謝します...この行を変更します:

add_action( 'wp_enqueue_scripts', 'myScripts' );

これに:

add_action( 'wp_enqueue_scripts', 'add_my_script' );

ページに表示されるエラーを解決しました。

残念ながら、コードはページ上で発火していないようです。(document).ready であるため、自動的に起動する必要があると思います (直接インクルードしたときと同じように) が、この方法でスクリプトをインクルードした場合はそうではありません。うーん...考え?

4

1 に答える 1