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

Einfaches Hinzufügen von JavaScript in WordPress-Seiten oder -Beiträgen (2 Methoden)

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 JavaScript in Ihre WordPress-Seiten oder -Beiträge einfügen?

Manchmal müssen Sie JavaScript-Code zu Ihrer gesamten Website oder zu bestimmten Seiten und Beiträgen hinzufügen. Standardmäßig können Sie in WordPress keinen Code direkt in Ihre Beiträge einfügen.

In diesem Artikel zeigen wir Ihnen, wie Sie JavaScript ganz einfach in WordPress-Seiten oder -Beiträge einfügen können.

How to easily add JavaScript in WordPress pages or posts (3 methods)

Was ist JavaScript?

JavaScript ist eine Programmiersprache, die im Browser des Benutzers und nicht auf dem Server ausgeführt wird. Diese clientseitige Programmierung ermöglicht es Entwicklern, eine Menge cooler Dinge zu tun, ohne Ihre Website zu verlangsamen.

Wenn Sie einen Videoplayer, einen Taschenrechner oder einen anderen Dienst eines Drittanbieters einbetten möchten, werden Sie häufig aufgefordert, einen JavaScript-Code in Ihre WordPress-Website zu kopieren und einzufügen.

Ein typisches JavaScript-Codefragment kann wie folgt aussehen:

<script type="text/javascript"> 
// Some JavaScript code
</script>

<!-- Another Example: --!>  
<script type="text/javascript" src="/path/to/some-script.js"></script>

Wenn Sie jedoch einem WordPress-Beitrag oder einer Seite ein JavaScript-Codefragment hinzufügen, wird es von WordPress gelöscht, wenn Sie versuchen, es zu speichern.

Sehen wir uns also an, wie Sie JavaScript ganz einfach zu WordPress-Seiten oder -Beiträgen hinzufügen können, ohne Ihre Website zu zerstören. Sie können die unten stehenden Links verwenden, um direkt zur gewünschten Methode zu gelangen.

Methode 1. Hinzufügen von JavaScript an beliebiger Stelle auf Ihrer WordPress-Website mit WPCode (empfohlen)

Manchmal müssen Sie für ein Plugin oder Tool einen JavaScript-Code kopieren und in Ihre Website einfügen, damit es richtig funktioniert.

Normalerweise werden diese Skripte in der Kopf- oder Fußzeile Ihres WordPress-Blogs platziert, so dass der Code bei jedem Seitenaufruf geladen wird.

Wenn Sie zum Beispiel Google Analytics installieren, muss der Code auf jeder Seite Ihrer Website ausgeführt werden, damit er die Besucher Ihrer Website erfassen kann.

Sie können den Code manuell in Ihre Dateien header.php oder footer.php einfügen, aber diese Änderungen werden überschrieben, wenn Sie Ihr Theme aktualisieren oder ändern.

Aus diesem Grund empfehlen wir die Verwendung von WPCode, um JavaScript überall auf Ihrer WordPress-Website hinzuzufügen.

WPCode ist das leistungsstärkste Code-Snippet-Plugin, das für WordPress verfügbar ist. Damit können Sie ganz einfach benutzerdefinierten Code zu jedem Bereich Ihrer Website hinzufügen, und das Beste ist, dass es kostenlos ist.

Zunächst müssen Sie das kostenlose WPCode-Plugin installieren und aktivieren. Weitere Einzelheiten finden Sie in unserer Schritt-für-Schritt-Anleitung für die Installation eines WordPress-Plugins.

Nach der Aktivierung müssen Sie zu Code Snippets “ Headers & Footer gehen.

Hier sehen Sie drei separate Felder mit den Bezeichnungen „Kopfzeile“, „Textkörper“ und „Fußzeile“.

Adding header & footer code snippets with WPCode

Sie können nun Ihren JavaScript-Code in eines dieser Felder einfügen und dann einfach auf die Schaltfläche „Speichern“ klicken. WPCode lädt nun automatisch den Code, den Sie auf jeder Seite Ihrer Website hinzugefügt haben.

Sie können Code-Snippets auch an jeder anderen Stelle Ihrer Website einfügen, beispielsweise innerhalb von Beiträgen oder Seiten.

Gehen Sie dazu einfach auf Code Snippets “ + Snippet hinzufügen und klicken Sie dann auf „Eigene erstellen“.

Create your own code snippet with WPCode

Nun wird eine Seite „Benutzerdefiniertes Snippet erstellen“ angezeigt, auf der Sie einen Titel für Ihren Code hinzufügen und ihn in das Feld „Codevorschau“ einfügen können.

Wählen Sie anschließend aus dem Dropdown-Menü „Code-Typ“ die Option „JavaScript Snippet“.

Enter a jQuery/JavaScript snippet into WPCode

Blättern Sie dann einfach weiter, bis Sie den Abschnitt „Einfügung“ finden.

Jetzt müssen Sie nur noch einen „Ort“ für den Code aus dem Dropdown-Menü auswählen. Suchen Sie „Seite, Beitrag, benutzerdefinierter Beitragstyp“ und wählen Sie die Stelle auf der Seite oder im Beitrag, an der der Code erscheinen soll.

Insert snippet before post in WPCode

Wenn Sie sich dafür entscheiden, dass WPCode das Snippet vor oder nach einem Absatz einfügt, können Sie auswählen, vor oder nach welchem Absatz im Beitrag es erscheinen soll.

Wenn Sie z. B. 1 in das Feld „Nummer einfügen“ eingeben, erscheint das Codeschnipsel vor oder nach dem ersten Absatz. Verwenden Sie 2 für den zweiten Absatz und so weiter.

Danach müssen Sie nur noch auf den Kippschalter am oberen Bildschirmrand klicken, um auf „Aktiv“ umzuschalten, und dann auf die Schaltfläche „Snippet speichern“ daneben klicken.

Activate and save snippet in WPCode

Das ist alles, was Sie brauchen, um Ihr Codeschnipsel auf der Website live zu schalten!

Methode 2. Manuelles Hinzufügen von JavaScript-Code zu WordPress mit Code (Fortgeschrittene)

Bei dieser Methode müssen Sie Code in Ihre WordPress-Dateien einfügen. Wenn Sie dies noch nicht getan haben, lesen Sie unsere Anleitung zum Kopieren und Einfügen von Code in WordPress.

Zunächst zeigen wir Ihnen, wie Sie den Code in den Header Ihrer WordPress-Website einfügen. Kopieren Sie den folgenden Code und fügen Sie ihn in Ihre functions.php ein.

function wpb_hook_javascript() {
    ?>
        <script>
          // your javscript code goes
        </script>
    <?php
}
add_action('wp_head', 'wpb_hook_javascript');

Hinzufügen von JavaScript zu einem bestimmten WordPress-Beitrag mithilfe von Code

Wenn Sie JavaScript nur zu einem einzigen WordPress-Beitrag hinzufügen möchten, müssen Sie den Code um eine bedingte Logik erweitern.

Werfen Sie einen Blick auf den folgenden Codeausschnitt:

function wpb_hook_javascript() {
  if (is_single ('5')) { 
    ?>
        <script type="text/javascript">
          // your javscript code goes here
        </script>
    <?php
  }
}
add_action('wp_head', 'wpb_hook_javascript');

Der obige Code führt das JavaScript nur aus, wenn die Beitrags-ID mit „5“ übereinstimmt. Stellen Sie sicher, dass Sie die „5“ durch Ihre eigene Beitrags-ID ersetzen.

Um die Beitrags-ID zu finden, öffnen Sie den Beitrag, in dem Sie das JavaScript ausführen möchten. In der URL der Seite finden Sie dann die Beitrags-ID.

Find WordPress post ID

Hinzufügen von JavaScript zu einer bestimmten WordPress-Seite mithilfe von Code

Wenn Sie JavaScript nur zu einer einzelnen WordPress-Seite hinzufügen möchten, müssen Sie dem Code bedingte Logik hinzufügen, wie oben beschrieben.

Schauen Sie sich das folgende Beispiel an:

function wpb_hook_javascript() {
  if (is_page ('10')) { 
    ?>
        <script type="text/javascript">
          // your javscript code goes here
        </script>
    <?php
  }
}
add_action('wp_head', 'wpb_hook_javascript');

Der obige Code führt das JavaScript nur aus, wenn die Seiten-ID „10“ lautet. Stellen Sie sicher, dass Sie die „10“ durch Ihre eigene Seiten-ID ersetzen.

Sie können die Seiten-ID mit der gleichen Methode wie oben finden. Öffnen Sie einfach die Seite, auf der das JavaScript ausgeführt werden soll, und notieren Sie die Seiten-ID in der URL.

Hinzufügen von JavaScript zu einem bestimmten WordPress-Beitrag oder einer Seite mithilfe von Code in der Fußzeile

Wenn Sie möchten, dass das JavaScript in der Fußzeile statt in der Kopfzeile Ihrer Website ausgeführt wird, können Sie den folgenden Codeschnipsel in Ihre Website einfügen.

function wpb_hook_javascript_footer() {
    ?>
        <script>
          // your javscript code goes
        </script>
    <?php
}
add_action('wp_footer', 'wpb_hook_javascript_footer');

Dieses Codeschnipsel wird in wp_footer statt in wp_head eingebunden. Sie können auch bedingte Tags hinzufügen, um JavaScript zu bestimmten Beiträgen und Seiten hinzuzufügen, wie in den obigen Beispielen.

Hinweis: Diese Methoden sind für Anfänger und Website-Besitzer gedacht. Wenn Sie die Entwicklung von WordPress-Themen oder -Plugins erlernen, müssen Sie JavaScript und Stylesheets ordnungsgemäß in Ihre Projekte einreihen.

Wir hoffen, dass dieser Artikel Ihnen geholfen hat zu lernen, wie Sie JavaScript zu WordPress-Seiten oder -Beiträgen hinzufügen können. Vielleicht interessieren Sie sich auch für unseren Leitfaden zur Auswahl der besten Blogging-Plattform und unsere Expertenauswahl der besten AI-Chatbot-Software für Ihre Website.

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

58 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. wing says

    i wonder why not use the most simple method, just directly use the wordpress „Custom HTML“ block to insert Javascript code to a post or page. I have try it and test it. No problem. very very very simple method.

    • WPBeginner Support says

      It would depend on the specific code, the methods we show in this guide are to add the code to the head section as most JavaScript wants to be run in the head section.

      Admin

  3. Rejane says

    I have an active child theme and I used the „Insert Headers and Footer“ plugin to add a JavaScript code for an email marketing service. It worked out! But unfortunately, I had to cancelled my account with this service and now I would like to remove the JavaScript code. How do I do this when I am using a child theme? Is there any easy way or another plugin for this?

    • WPBeginner Support says

      You would remove the code from the Insert Headers and Footers plugin and it would remove the code from your site :)

      Admin

    • WPBeginner Support says

      It should be at the top of the edit page. if you are using the classic editor then it would be under Screen Options.

      Admin

  4. Eleni says

    I’m not getting the Custom Fields option in the Screen Options tab. I’m using a self-hosted website and have installed and activated the Code Embed plugin

  5. Ashley says

    This site is AMAZING!!! This is the third post in a row where I’ve hit the jackpot getting what I needed and did it in the easiest way possible. Thank you!!

  6. Dude says

    Hey, great stuff WPbeginners! The second method worked like a charm. I did have a question though. If I wanted to add another js code for another purpose, how should the code start. Because anything I add after the code is greyed out. I’m at a loss here. I want it to do the same but for another page. Any ideas will be appreciated.

    • WPBeginner Support says

      It would heavily depend on the code you are using but you would want to ensure the code is before the /script tag

      Admin

  7. Martin says

    Question on Method 3:

    After inputting the value and clicking on the „add custom field“, how do I get the code to display on my website frontend?

    Should I insert „{{CODEmyjscode}}“ using a shortcode widget or text editor on the page?

  8. Bret Bernhoft says

    When I first began working with WordPress, JavaScript seemed like an impossibility for me. But fast forward to today and I’m writing the language every day; often in association with WordPress.

    I wish it had been clearer to me how easy it would have been to write JavaScript, when I first began this journey. Thank you for the tools and tips. I’ll have to give this a try.

  9. Kat says

    I tried adding custom JS in my post, but nothing happens. I followed your exact directions for Method 3, but when I go to preview the page it’s just blank space where the JS is supposed to be. Any idea why?

    • WPBeginner Support says

      You would want to take a look at the plugin’s FAQ for the most common reasons for that issue and how to resolve it.

      Admin

  10. Samuel says

    How does this work with the new WordPress block system?

    I’m trying to embed this in a page, but it just shows as {{code1}} on the preview

    • WPBeginner Support says

      It would depend on the method you are using on your site for the plugin, they have an update in their FAQ section for how to use it at the moment.

      Admin

  11. James says

    Hi. I have employed a programmer to create a tool, which he did in Javascript. I have been using Weebly but Weebly has become unresponsive to requests for help, to which hundreds of blogs testify. So, I’m looking at alternatives to Weebly. Could WordPress handle a 2 MB javascript tool?

    Thanks,

    • WPBeginner Support says

      Your hosting would determine if a tool like that could be used not the platform for your website and depending on how the tool was set up would determine if you can transfer the tool.

      Admin

  12. Matt says

    What if I need to add the script just on a single page but in the head not the body? I am trying to add a google conversion pixel just to my form submit thank you page.

    • WPBeginner Support says

      You would want to take a look at the section of the article called: Adding JavaScript to a Specific WordPress Post or Page Using Code :)

      Admin

  13. Manjeet Chhillar says

    Thank you for this very helpful post.

    My query is: How can I implement „Method 2“ on multiple posts. Do i need to add Post ID of every single post separated by comma?

    • WPBeginner Support says

      yes, you would need to place the commas outside the single quotes and start a new set of quotes for this method

      Admin

  14. Deborah says

    Thank you for sharing the three methods WordPress users can use to add JavaScript to posts or pages. From what I read on the Insert Headers and Footers plugin page in the repository, the plugin doesn’t use the enqueue method to add the scripts. Which is the recommended method to add scripts in WordPress.

    Did I misunderstand? Or is Insert Headers and Footers using enqueue to add scripts? If it’s not using enqueue, do you know when the plugin will be updated to use enqueue?

    • WPBeginner Support says

      The plugin is not enqueueing scripts added to it at the moment as not everything added with our plugin may not want to be enqueued. If you would like to enqueue the added code you would want to use another method.

      Admin

  15. Dave G says

    Nice, thanks for that. It so happen that the exact post ID I needed to run javascript on was number 16. „`if (is_single (’16‘)) { „`

    Are you from the future?

    :)

  16. Thomas says

    I need to add a script to all posts in my blog. I have the plugin to each individual post. Thing is, there are thousands of posts and we need to add the script to all of them. Any suggestions? Thank you in advance.

    • WPBeginner Support says

      The Insert Headers and footers option will put a code on every post and page for you if they are using the same code.

      Admin

        • WPBeginner Support says

          If you had a widget that is only added to posts you could try adding the code in a widget.

    • WPBeginner Support says

      It would depend on the specific code you are adding to the site for the possible reasons it could not be working. You may want to ensure with who you took the code from that the code itself is working.

      Admin

  17. Remco says

    Thank you for this great post!
    Is it possible to implement Structured Data on Woocommerce pages with this method (JSON-LD)?

    • WPBeginner Support says

      You likely could but if you have an SEO plugin you are currently using you would want to check with that plugin to see if the plugin does that already.

      Admin

  18. graham says

    A well-presented roundup of the better-known options for what is becoming a common need. However, many WordPress users are not (and do not want to be) programmers. For them, JavaScript in any form is too frightening; that’s why they use WordPress with its promise of „no programming required“.

    There’s another possibility; to use custom scripts instead of JavaScript, and embed them directly in the page. You can put them in any component, though I prefer .

    All you need then is something that can compile and run the script. It’s hard to find plugins that can do this; my own searches haven’t yet turned up any. However, as a JavaScript programmer myself, I was able to write one and put it in the library as EasyCoder. The scripts resemble English, have about the same complexity as SQL and can do most of the things commonly required to manage content and interactivity in a web page. EasyCoder is also fully pluggable so other programmers can add modules themselves.

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.