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

Jak łatwo dodać JavaScript na stronach lub wpisach WordPress (2 metody)

Uwaga redakcyjna: Otrzymujemy prowizję z linków partnerskich na WPBeginner. Prowizje nie mają wpływu na opinie i oceny naszych redaktorów. Dowiedz się więcej o Proces redakcyjny.

Czy chcesz dodać JavaScript do twoich stron lub wpisów WordPress?

Czasami może zajść potrzeba dodania kodu JavaScript do całej twojej witryny internetowej lub do określonych stron i wpisów. Domyślnie WordPress nie pozwala na dodawanie kodu bezpośrednio do twoich wpisów.

W tym artykule pokażemy, jak łatwo dodać JavaScript do stron lub wpisów WordPress.

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

Czym jest JavaScript?

JavaScript to język programowania, który działa w przeglądarce użytkownika, a nie na twoim serwerze. Programowanie po stronie klienta pozwala programistom robić wiele fajnych rzeczy bez spowalniania twojej witryny internetowej.

Jeśli chcesz osadzać odtwarzacz filmów, dodawać kalkulatory lub inne usługi stron trzecich, często będziesz proszony o skopiowanie i wklejenie fragmentu kodu JavaScript do twojej witryny internetowej WordPress.

Typowy fragment kodu JavaScript może wyglądać następująco:

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

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

Jeśli jednak dodasz fragment kodu JavaScript do wpisu lub strony WordPress, zostanie on usunięty przez WordPress, gdy spróbujesz go zapisać.

Mając to na uwadze, zobaczmy, jak łatwo dodać JavaScript do stron lub wpisów WordPress bez niszczenia twojej witryny internetowej. Możesz skorzystać z poniższych odnośników, aby przejść bezpośrednio do wybranej metody.

Metoda 1. Dodaj JavaScript w dowolnym miejscu Twojej witryny WordPress za pomocą WPCode (zalecane)

Czasami wtyczka lub narzędzie wymaga skopiowania i wklejenia fragmentu kodu JavaScript na twoją witrynę internetową, aby działała poprawnie.

Zazwyczaj skrypty te są umieszczane w nagłówku lub stopce twojego bloga WordPress, dzięki czemu kod jest wczytywany przy każdym zobaczeniu strony.

Na przykład, gdy instalujesz Google Analytics, kod musi działać na każdej stronie twojej witryny internetowej, aby mógł śledzić odwiedzających twoją witrynę.

Możesz ręcznie dodać kod do plików header.php lub footer. php, ale zmiany te zostaną nadpisane po aktualizacji lub zmianie twojego motywu.

Dlatego zalecamy używanie WPCode do dodawania JavaScript w dowolnym miejscu na twojej witrynie WordPress.

WPCode to najpotężniejsza wtyczka do fragmentów kodu dostępna dla WordPressa. Umożliwia ona łatwe dodawanie własnego kodu do dowolnego obszaru twojej witryny, a co najlepsze, jest darmowa.

Najpierw należy zainstalować i włączyć darmową wtyczkę WPCode. Aby uzyskać więcej informacji, zobacz nasz przewodnik krok po kroku, jak zainstalować wtyczkę WordPress.

Po włączaniu należy przejść do sekcji Fragmenty kodu ” Nagłówki i stopki.

Tutaj zobaczysz trzy oddzielne pola oznaczone jako „Nagłówek”, „Treść” i „Stopka”.

Adding header & footer code snippets with WPCode

Możesz teraz dodać twój kod JavaScript do jednego z tych pól, a następnie po prostu kliknąć przycisk „Zapisz”. WPCode będzie teraz automatycznie wczytywać dodany kod na każdej stronie twojej witryny internetowej.

Możesz także dodawać fragmenty kodu do dowolnego innego miejsca na twojej witrynie, np. wewnątrz wpisów lub stron.

Aby to zrobić, wystarczy przejść do sekcji Fragmenty kodu ” + Dodaj fragment kodu, a następnie kliknąć „Utwórz swój własny”.

Create your own code snippet with WPCode

Zobaczysz teraz stronę „Utwórz własny fragment kodu”, na której możesz dodać tytuł dla twojego kodu i wkleić go w polu „Podgląd kodu”.

Następnie wybierz „Fragment kodu JavaScript” z rozwijanego menu „Rodzaj kodu”.

Enter a jQuery/JavaScript snippet into WPCode

Następnie przewijaj, aż znajdziesz sekcję „Wstaw”.

Wszystko, co musisz teraz zrobić, to wybrać „Położenie” dla kodu z rozwijanego menu. Znajdź „Stronę, wpis, własny typ treści” i wybierz, gdzie na stronie lub we wpisie ma pojawić się kod.

Insert snippet before post in WPCode

Jeśli zdecydujesz się na wstawienie fragmentu kodu przed lub po akapicie, będziesz mógł wybrać, przed którym konkretnym akapitem we wpisie ma się on pojawić.

Na przykład, jeśli umieścisz 1 w polu „Wstaw numer”, fragment kodu pojawi się przed lub po pierwszym akapicie. Użyj 2 dla drugiego akapitu i tak dalej.

Następnie wystarczy kliknąć przełącznik w górnej części ekranu, aby przełączyć na „Włączanie”, a następnie kliknąć przycisk „Zapisz fragment kodu” obok niego.

Activate and save snippet in WPCode

To wszystko, czego potrzeba, aby twój fragment kodu działał na witrynie!

Metoda 2. Ręczne dodawanie kodu JavaScript do WordPress za pomocą kodu (zaawansowane)

W tej metodzie musisz dodać kod do twoich plików WordPress. Jeśli nie robiłeś tego wcześniej, zapoznaj się z naszym przewodnikiem na temat kopiowania i wklejania kodu w WordPress.

Najpierw pokażemy ci, jak dodać kod do nagłówka twojej witryny WordPress. Musisz skopiować poniższy kod i dodać go do twojego functions.php.

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

Dodawanie JavaScript do konkretnego wpisu WordPress za pomocą kodu

Jeśli chcesz dodać JavaScript tylko do pojedynczego wpisu WordPress, będziesz musiał dodać logikę warunkową do kodu.

Spójrz na poniższy fragment kodu:

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');

Powyższy kod uruchomi JavaScript tylko wtedy, gdy identyfikator wpisu pasuje do „5”. Upewnij się, że zastąpiłeś '5′ twoim identyfikatorem wpisu.

Aby znaleźć identyfikator wpisu, otwórz wpis, w którym chcesz uruchomić JavaScript. Następnie w adresie URL strony znajdziesz identyfikator wpisu.

Find WordPress post ID

Dodawanie JavaScript do określonej strony WordPress za pomocą kodu

Jeśli chcesz dodać JavaScript tylko do jednej strony WordPressa, będziesz musiał dodać logikę warunkową do kodu, tak jak powyżej.

Spójrzmy na poniższy przykład:

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');

Powyższy kod uruchomi JavaScript tylko wtedy, gdy identyfikator strony to „10”. Upewnij się, że zastąpiłeś ’10’ twoim identyfikatorem strony.

Identyfikator strony można znaleźć za pomocą tej samej metody, co powyżej. Po prostu otwórz stronę, na której chcesz uruchomić JavaScript i zanotuj identyfikator strony w adresie URL.

Dodawanie JavaScript do konkretnego wpisu WordPress lub strony za pomocą kodu w stopce

Jeśli chcesz, aby JavaScript był uruchamiany w stopce witryny zamiast w nagłówku, możesz dodać następujący fragment kodu do swojej witryny internetowej.

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

Ten fragment kodu zahacza o wp_footer zamiast wp_head. Możesz także dodać tagi warunkowe, aby dodać JavaScript do określonych wpisów i stron, jak w powyższych przykładach.

Uwaga: Te metody są przeznaczone dla początkujących i właścicieli witryn internetowych. Jeśli uczysz się tworzenia motywów lub wtyczek WordPress, to musisz odpowiednio enkejtować JavaScript i arkusze stylów w swoich projektach.

Mamy nadzieję, że ten artykuł pomógł ci dowiedzieć się, jak łatwo dodać JavaScript do stron lub wpisów WordPress. Zachęcamy również do zapoznania się z naszym przewodnikiem na temat wyboru najlepszej platformy do blogowania oraz z naszym wyborem najlepszych chatbotów AI dla twojej witryny internetowej.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Ujawnienie: Nasze treści są wspierane przez czytelników. Oznacza to, że jeśli klikniesz na niektóre z naszych linków, możemy otrzymać prowizję. Zobacz jak WPBeginner jest finansowany, dlaczego to ma znaczenie i jak możesz nas wspierać. Oto nasz proces redakcyjny.

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Najlepszy zestaw narzędzi WordPress

Uzyskaj BEZPŁATNY dostęp do naszego zestawu narzędzi - zbiór produktów i zasobów związanych z WordPressem, które każdy profesjonalista powinien mieć!

Reader Interactions

60 komentarzyZostaw odpowiedź

  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. Jiří Vaněk says

    WPCode saved my entire website like this, which I already had completed, but eventually we found out that the menu works very poorly on mobile devices. I found a solution in the form of JavaScript, but I didn’t know where or how to insert it into the website. This saved me all the work and solved the problem with closing the menu on mobile devices.

  3. 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.

      Administrator

  4. 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 :)

      Administrator

    • 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.

      Administrator

  5. 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.

      Administrator

  6. 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!!

  7. 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

      Administrator

  8. 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?

  9. 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.

  10. 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.

      Administrator

  11. 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.

      Administrator

  12. 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.

      Administrator

  13. 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 :)

      Administrator

  14. 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

      Administrator

  15. 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.

      Administrator

  16. 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?

    :)

  17. 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.

      Administrator

      • 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.

    • 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.

      Administrator

    • WPBeginner Support says

      Our plugin is currently working from testing but we will certainly take another look at it.

      Administrator

  18. 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.

      Administrator

  19. 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.

Zostaw odpowiedź

Dziękujemy za pozostawienie komentarza. Pamiętaj, że wszystkie komentarze są moderowane zgodnie z naszymi polityka komentarzy, a Twój adres e-mail NIE zostanie opublikowany. NIE używaj słów kluczowych w polu nazwy. Przeprowadźmy osobistą i konstruktywną rozmowę.