Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPB Cup
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Wie man JavaScripts und Styles in WordPress richtig hinzufügt

Hinweis der Redaktion: Wir erhalten eine Provision für Partnerlinks auf WPBeginner. Die Provisionen haben keinen Einfluss auf die Meinung oder Bewertung unserer Redakteure. Erfahre mehr über Redaktioneller Prozess.

Möchten Sie lernen, wie man JavaScripts und CSS-Stylesheets richtig in WordPress einfügt?

Viele Heimwerker machen oft den Fehler, ihre Skripte und Stylesheets direkt in Plugins und Themes aufzurufen.

In diesem Artikel zeigen wir Ihnen, wie Sie JavaScript und Stylesheets in WordPress richtig hinzufügen. Dies ist besonders nützlich für diejenigen, die gerade erst anfangen, die Entwicklung von WordPress-Themes und -Plugins zu lernen.

Properly adding JavaScripts and styles in WordPress

Häufige Fehler beim Hinzufügen von Skripten und Stylesheets in WordPress

Viele neue WordPress-Plugins und Theme-Entwickler machen den Fehler, ihre Skripte oder Inline-CSS direkt in ihre Plugins und Themes einzufügen.

Manche verwenden fälschlicherweise die Funktion wp_head, um ihre Skripte und Stylesheets zu laden.

<?php
add_action('wp_head', 'wpb_bad_script');
function wpb_bad_script() {
echo 'jQuery goes here';
}
?>

Der obige Code mag zwar einfacher erscheinen, ist aber der falsche Weg, um Skripte in WordPress hinzuzufügen, und führt zu mehr Konflikten in der Zukunft.

Wenn Sie z. B. jQuery manuell laden und ein anderes Plugin jQuery mit der richtigen Methode lädt, wird jQuery zweimal geladen. Wenn es auf jeder Seite geladen wird, wirkt sich dies negativ auf die Geschwindigkeit und Leistung von WordPress aus.

Es ist auch möglich, dass es sich um unterschiedliche Versionen handelt, was ebenfalls zu Konflikten führen kann.

Schauen wir uns also an, wie man Skripte und Stylesheets richtig hinzufügt.

Warum Skripte und Stile in WordPress in die Warteschlange stellen?

WordPress hat eine starke Entwicklergemeinschaft. Tausende von Menschen aus der ganzen Welt entwickeln Themes und Plugins für WordPress.

Um sicherzustellen, dass alles ordnungsgemäß funktioniert und niemand dem anderen auf die Füße tritt, verfügt WordPress über ein Enqueuing-System. Dieses System bietet eine programmierbare Möglichkeit zum Laden von JavaScripts und CSS-Stylesheets.

Mit den Funktionen wp_enqueue_script und wp_enqueue_style teilen Sie WordPress mit, wann eine Datei geladen werden soll, wo sie geladen werden soll und welche Abhängigkeiten sie hat.

Dieses System ermöglicht es Entwicklern auch, die in WordPress integrierten JavaScript-Bibliotheken zu nutzen, anstatt das gleiche Skript eines Drittanbieters mehrfach zu laden. Dies verkürzt die Ladezeit der Seite und hilft, Konflikte mit anderen Themes und Plugins zu vermeiden.

Wie kann man Skripte in WordPress richtig einreihen?

Das richtige Laden von Skripten in WordPress ist sehr einfach. Im Folgenden finden Sie einen Beispielcode, den Sie in Ihre Plugin-Datei, in die functions.php-Datei Ihres Themes oder in ein Code-Snippets-Plugin einfügen, um Skripte in WordPress richtig zu laden.

?php
function wpb_adding_scripts() {
 
wp_register_script('my_amazing_script', plugins_url('amazing_script.js', __FILE__), array('jquery'),'1.1', true);
 
wp_enqueue_script('my_amazing_script');
}
  
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );  
?>

Erläuterung:

Zunächst haben wir unser Skript mit der Funktion wp_register_script() registriert. Diese Funktion akzeptiert 5 Parameter:

  • $handle – Handle ist der eindeutige Name Ihres Skripts. Unseres heißt „my_amazing_script“.
  • $src – src ist der Ort, an dem sich Ihr Skript befindet. Wir verwenden die Funktion plugins_url, um die richtige URL unseres Plugins-Ordners zu erhalten. Sobald WordPress diesen findet, sucht es in diesem Ordner nach dem Dateinamen amazing_script.js.
  • $deps – deps steht für dependency. Da unser Skript jQuery verwendet, haben wir jQuery im Abhängigkeitsbereich hinzugefügt. WordPress wird jQuery automatisch laden, wenn es nicht bereits auf der Website geladen ist.
  • $ver – Dies ist die Versionsnummer unseres Skripts. Dieser Parameter ist nicht erforderlich.
  • $in_footer – Wir wollen unser Skript in die Fußzeile laden, also haben wir den Wert auf true gesetzt. Wenn Sie das Skript in der Kopfzeile laden wollen, müssen Sie den Wert auf false setzen.

Nachdem wir alle Parameter in wp_register_script angegeben haben, können wir das Skript einfach in wp_enqueue_script() aufrufen, was alles in Gang setzt.

Der letzte Schritt ist die Verwendung des Aktionshakens wp_enqueue_scripts, um das Skript tatsächlich zu laden. Da es sich um einen Beispielcode handelt, haben wir diesen direkt unter allem anderen hinzugefügt.

Wenn Sie dies zu Ihrem Thema oder Plugin hinzufügen, können Sie diesen Aktionshaken dort platzieren, wo das Skript tatsächlich benötigt wird. So können Sie den Speicherbedarf Ihres Plugins verringern.

Nun werden sich einige fragen, warum wir den zusätzlichen Schritt machen, das Skript zuerst zu registrieren und es dann in die Warteschlange zu stellen? Nun, dies ermöglicht es anderen Website-Besitzern, Ihr Skript abzumelden, ohne den Kerncode Ihres Plugins zu verändern.

Stile in WordPress ordnungsgemäß einreihen

Genau wie Skripte können Sie auch Ihre Stylesheets in die Warteschlange stellen. Sehen Sie sich das folgende Beispiel an:

<?php
function wpb_adding_styles() {
wp_register_style('my_stylesheet', plugins_url('my-stylesheet.css', __FILE__));
wp_enqueue_style('my_stylesheet');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_styles' );  
?>

Anstelle von wp_enqueue_script verwenden wir jetzt wp_enqueue_style, um unser Stylesheet hinzuzufügen.

Beachten Sie, dass wir den Aktionshaken wp_enqueue_scripts sowohl für Stile als auch für Skripte verwendet haben. Trotz des Namens funktioniert diese Funktion für beide.

In den obigen Beispielen haben wir die Funktion plugins_url verwendet, um auf den Speicherort des Skripts oder Stils zu verweisen, den wir in die Warteschlange stellen wollten.

Wenn Sie jedoch die Funktion enqueue scripts in Ihrem Theme verwenden, benutzen Sie stattdessen einfach get_template_directory_uri(). Wenn Sie mit einem Child-Theme arbeiten, dann verwenden Sie get_stylesheet_directory_uri().

Nachstehend finden Sie einen Beispielcode:

<?php
  
function wpb_adding_scripts() {
wp_register_script('my_amazing_script', get_template_directory_uri() . '/js/amazing_script.js', array('jquery'),'1.1', true);
wp_enqueue_script('my_amazing_script');
}
  
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );  
?>

Wir hoffen, dass dieser Artikel Ihnen geholfen hat zu lernen, wie man JavaScript und Styles in WordPress richtig hinzufügt. Vielleicht möchten Sie auch den Quellcode der wichtigsten WordPress-Plugins studieren, um einige praktische Code-Beispiele zu finden, oder Sie lesen unseren Leitfaden zum einfachen Hinzufügen von JavaScript in WordPress-Beiträge oder -Seiten.

Wenn Ihnen dieser Artikel gefallen hat, dann abonnieren Sie bitte unseren YouTube-Kanal für WordPress-Videotutorials. Sie können uns auch auf Twitter und Facebook finden.

Offenlegung: Unsere Inhalte werden von unseren Lesern unterstützt. Das bedeutet, dass wir möglicherweise eine Provision verdienen, wenn Sie auf einige unserer Links klicken. Mehr dazu erfahren Sie unter Wie WPBeginner finanziert wird , warum das wichtig ist und wie Sie uns unterstützen können. Hier finden Sie unseren redaktionellen Prozess .

Das ultimative WordPress Toolkit

Erhalte KOSTENLOSEN Zugang zu unserem Toolkit - eine Sammlung von WordPress-bezogenen Produkten und Ressourcen, die jeder Profi haben sollte!

Reader Interactions

36 KommentareEine Antwort hinterlassen

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Jean-Michel says

    Hi there,
    I followed what is said here but now I get an empty white page on my web site. Could someone give me a hint ?
    Thanks

  3. Zaved Hossain says

    This is nice, though my usual practice is to add wp_enqueue_script/style in a single line without registering. Coders need to be careful about the parameters, perhaps a little explanation of that would be helpful. For example, the different versions of jquery (your jquery script may require different version than the wordpress‘) and where to add it (header or footer which is determined by the true/false parameter). The jquery script needs to be added in the header, (hence a ‚false‘ needs to be passed as the param value), otherwise it may not work.

  4. Hansjörg Leichsenring says

    There are often a lot of style.css.
    How can I ensure the correct load-order with enque and make sure, that the child css is loaded last?

    Cheers from Germany
    Hansjörg

  5. Carlos Araya says

    How do I pass empty parameter to register_script? I want to make sure that they script is loaded at the bottom of the page but can’t find information whether this is the default behavior or not

    • Kerry Beeher says

      Bonjour,

      Thank you for your excellente resource. Merci !!!

      I am little novice and just begin my journey to learn PHP and how WordPress use wp_enqueue_script and wp_register_script to add JavaScript and CSS.

      I use this free plugin called Easy Code Manager to help run through your exemples:
      however I am not sure if this is right plugin to use.

      I read before that it is not the best idea to modifier code in functions.php so I wonder if this is ok to do?

      Will it not get change on a theme update?
      Sorry for question, I still learn WordPress.

      Merci,
      Kerry

  6. Vaibhav Bansal says

    I want to add an Amazon Ad
    I tried to add it in text widget, but it shows blank.
    Below is the code-

    This is my site-
    Help me. How do I add js on my site?

  7. pradyumna says

    i have inserted a javascript using this plugin but now i have to remove it, i have tried uninstalling and deactivating the plugin but the javascript still executes

  8. Vijay.Rajpal says

    Hello Sir,
    I am using esteem theme and I wanted to add some javascripts functionality to my website like lightbox. I have created a child theme and the code are as follows. in the functions.php.

    and I am getting an error:-Parse error: syntax error, unexpected '{' in E:\InstantWP_4.5\iwpserver\htdocs\wordpress\wp-content\themes\esteem-child\functions.php on line 18
    Please Help I am using sublime as my text editor.
    Please Help!!!!!

  9. Pramod says

    hello…..
    i m adding .js file in js directory of wordpress and gives its reference of it in funcation.php
    but its not working

    wp_enqueue_script( ‚any-navigation‘, get_template_directory_uri() . ‚/js/menu.js‘);

  10. Bobbie says

    Thanks so much! I’ve been trying to add a custom .js file but this is the first explanation that the register_script was needed.

  11. colkav says

    Hey, great tutorial. I’m having an issue adding a Google Analytics related javascript, as described here:
    I’ve put the script in my child theme’s ‚js‘ folder (having first stripped the html from the code).

    When i load up the page I keep getting the error :

    ReferenceError: Can’t find variable: ga
    (anonymous function)myscript.js:6

    …and it just dawned on me that maybe I need to add ‚analytics.js‘ as a dependency!

    Does that sounds right? And if so, how would I add analytics as a dependency for my script? I’ve tried experimenting here to no avail :(

  12. xavi says

    Hi.
    thanks for this amazing post tutorial! But when you say „where to upload the script“ you just can define head or footer (in all entire webpages!)? Could you define an especific page to load it? I just need it in one. Thanks for advance and keep working! Cheers.

  13. Skye Barcus says

    I am a total novice at js but do know html. I want to put this on a wordpress page:

    Basically, it’s a widget to join a GoToMeeting. This works if you just throw it into the body of an html page, but in WordPress, it gets supressed.
    Can you give me a „For Dummies“ version of how to make this work?

  14. Dejan says

    I really like you site it is full of useful tips, however looks like you are not doing it „Properly“ for CSS enqueue even though your title say that way :=) The right way would be :

    wp_register_style( ‚my-css-style‘, get_template_directory_uri() . ‚/css/style.css‘, array(), ‚1.0‘, ‚all‘ );
    wp_enqueue_style( ‚my-css-style‘ );

    Keep up the good work… Cheers!

  15. Adrian Zumbrunnen says

    Thanks for the effort you put into this. It just feels wrong to have wp_enque_script for loading stylesheets. WordPress could eventually spit out script instead of the stylehseet syntax for it.

    Do you really embed that way?

    • WPBeginner Support says

      This tutorial shows how to load JavaScript and stylesheet files for your themes or plugins in WordPress. If by Embed you meant how we display code in articles, then we use Syntax Highlighter plugin for that.

      Admin

  16. oiveros says

    hi i’m kind of new on the wordpress theming , and reading about these topic, i wanted to ask you about something related to these . If i want to update the jquery library link how do i do it or where do i find the link i been trying to do it but i can’t find it. Thank you in advanced for your help

    • WPBeginner Support says

      If by updating jquery library link, you mean to add jquery from Google’s library. WordPress comes packed with jquery and to load it in your theme use this line in your theme:

      <?php wp_enqueue_script('jquery'); ?>

      Admin

      • oiveros says

        okey so if i want to have the latest jquery, i just use that line?, because somebody told me to use a plugin just for that, but i wanted to learn how to do it without a plugin

        • oliveros says

          Thank you for your answer, i found the post related to that issue here in your site.

  17. Elliott Richmond says

    Useful Syed, thanks.
    I recently had an issue loading a css file using _underscore as a framework, although the stylesheet was called mycustomstyles.css the theme was calling mycustomstyles.css?ver=xx and the theme wasn’t loading the file because of the naming of the file by appending ?ver=xx to the end of the name.
    Is that something to do with $ver default?

Eine Antwort hinterlassen

Danke, dass du einen Kommentar hinterlassen möchtest. Bitte beachte, dass alle Kommentare nach unseren kommentarpolitik moderiert werden und deine E-Mail-Adresse NICHT veröffentlicht wird. Bitte verwende KEINE Schlüsselwörter im Namensfeld. Lass uns ein persönliches und sinnvolles Gespräch führen.