您可以使用wp_head. 这将在头部插入脚本。
function dropin_location() {
    if ( is_page( 7 ) ) {
        ?>
        <script>alert(\'got here\')</script>\'
        <?php
    }
}
add_action(\'wp_head\', \'dropin_location\');
 但是,还有其他方法可以添加脚本。你可以把它作为一个脚本文件放在你的主题中,并将其排队,以便WordPress“知道”它。这样,它可以具有依赖性,在正确的时间加载,等等。
Here is an explanation.
所以如果你有my-killer-script.js 在主题中,可以执行以下操作:
wp_enqueue_script(
        \'some-script-handle\', // some name to give it
        get_theme_file_uri( \'/path/to/my-killer-script.js\' ), // file path to script
        array( \'some-dependency-handle\' ), // does this script need any dependencies? If so, add their handles, or leave the array empty.
        false, // do you need a version?
        true // load in footer? true/false
    );
Read the WP docs on wp_enqueue_script here.