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.
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“.
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“.
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“.
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.
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.
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.
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.
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!
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
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
Paul Liles says
I cannot find the three-dot menu anywhere? Need some help.
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
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
WPBeginner Support says
If you’re using the Block editor then the setting has moved under the preferences area.
Admin
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!!
WPBeginner Support says
Glad our guides were helpful
Admin
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
tagAdmin
Jonathan says
Thanks. This article was exceedingly helpful. I went with the functions.php option. Worked well.
WPBeginner Support says
Glad our guide was helpful
Admin
Elise says
That worked. Thank you so much!
WPBeginner Support says
You’re welcome
Admin
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?
WPBeginner Support says
for the moment you would want to use the text or code editor.
Admin
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.
WPBeginner Support says
Glad we could share some easy methods for adding JavaScript to your site!
Admin
ibrahim says
It worked and helped me a lot. Thank you!
WPBeginner Support says
You’re welcome
Admin
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
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
Akash says
Thank for this information. Really amazing and helpful post.
WPBeginner Support says
You’re welcome, glad our article was helpful
Admin
Alex says
Hey, great guide! The problem is I don’t have „Custom Fields“ under screen options… Any idea why?
WPBeginner Support says
Is your site on WordPress.com?
Admin
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
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
quy says
it works like magic. Thanks very much
WPBeginner Support says
You’re welcome, glad our article could help
Admin
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
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
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?
WPBeginner Support says
Not yet at least
Admin
Golu Arjun says
Thank you for this post. It’s very helpful. It is possible to customize
WPBeginner Support says
You’re welcome
Admin
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
Thomas says
Thank you for your quick reply.
We only want the script to run on Posts. We do not want it to run on all pages.
WPBeginner Support says
If you had a widget that is only added to posts you could try adding the code in a widget.
Ann says
I’ve tried using the Headers and Footers scripts and the jQuery just doesn’t seem to be working properly.
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
Andrew Golay says
Please fix your Headers / Footer plugin or change this article, thank you.
WPBeginner Support says
Our plugin is currently working from testing but we will certainly take another look at it.
Admin
lynn says
thank you!! This was very helpful .
WPBeginner Support says
Glad it was helpful
Admin
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
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.