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

WordPress’te JavaScripts ve Stiller Nasıl Doğru Şekilde Eklenir?

Editoryal Not: WPBeginner üzerindeki ortak bağlantılardan komisyon kazanıyoruz. Komisyonlar, editörlerimizin görüşlerini veya değerlendirmelerini etkilemez. Editoryal Süreç hakkında daha fazla bilgi edinin.

WordPress’e JavaScripts ve CSS stil sayfalarını nasıl düzgün bir şekilde ekleyeceğinizi öğrenmek ister misiniz?

Birçok DIY kullanıcısı, eklenti ve temalardaki komut dosyalarını ve stil sayfalarını doğrudan çağırma hatasına düşmektedir.

Bu makalede, WordPress’te JavaScript ve stil sayfalarını nasıl düzgün bir şekilde ekleyeceğinizi göstereceğiz. Bu, özellikle WordPress tema ve eklenti geliştirmeyi yeni öğrenmeye başlayanlar için faydalı olacaktır.

Properly adding JavaScripts and styles in WordPress

WordPress’te Betik ve Stil Sayfası Eklerken Sık Yapılan Hatalar

Birçok yeni WordPress eklentisi ve tema geliştiricisi, komut dosyalarını veya satır içi CSS’lerini eklentilerine ve temalarına doğrudan ekleme hatasına düşmektedir.

Bazıları komut dosyalarını ve stil sayfalarını yüklemek için yanlışlıkla wp_head işlevini kullanır.

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

Yukarıdaki kod daha kolay görünse de, WordPress’te komut dosyası eklemenin yanlış yoludur ve gelecekte daha fazla çakışmaya yol açar.

Örneğin, jQuery’yi manuel olarak yüklerseniz ve başka bir eklenti jQuery’yi uygun yöntemle yüklerse, jQuery iki kez yüklenmiş olur. Her sayfada yükleniyorsa, bu WordPress hızını ve performansını olumsuz etkileyecektir.

İkisinin farklı sürümler olması da mümkündür ve bu da çakışmalara neden olabilir.

Bununla birlikte, komut dosyaları ve stil sayfaları eklemenin doğru yoluna bir göz atalım.

WordPress’te Betikler ve Stiller Neden Sıkıştırılır?

WordPress güçlü bir geliştirici topluluğuna sahiptir. Dünyanın dört bir yanından binlerce kişi WordPress için temalar ve eklentiler geliştirmektedir.

Her şeyin düzgün çalıştığından ve kimsenin bir başkasının ayağına basmadığından emin olmak için WordPress’in bir sıralama sistemi vardır. Bu sistem JavaScripts ve CSS stil sayfalarını yüklemek için programlanabilir bir yol sağlar.

wp_enqueue_script ve wp_enqueue_style işlevlerini kullanarak WordPress’e bir dosyanın ne zaman yükleneceğini, nereye yükleneceğini ve bağımlılıklarının neler olduğunu söylersiniz.

Bu sistem ayrıca geliştiricilerin aynı üçüncü taraf komut dosyasını birden çok kez yüklemek yerine WordPress ile birlikte gelen yerleşik JavaScript kitaplıklarını kullanmalarına olanak tanır. Bu, sayfa yükleme süresini azaltır ve diğer temalar ve eklentilerle çakışmaları önlemeye yardımcı olur.

WordPress’te Komut Dosyalarını Düzgün Bir Şekilde Nasıl Sıraya Sokabilirim?

WordPress’te komut dosyalarını düzgün bir şekilde yüklemek çok kolaydır. Aşağıda, WordPress’te komut dosyalarını düzgün bir şekilde yüklemek için eklentiler dosyanıza, temanızın functions.php dosyasına veya bir kod parçacıkları eklentisine yapıştıracağınız örnek bir kod bulunmaktadır.

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

Açıklama:

Kodumuzu wp_register_script() fonksiyonu aracılığıyla kaydederek başladık. Bu fonksiyon 5 parametre kabul eder:

  • $handle – Handle, betiğinizin benzersiz adıdır. Bizimkinin adı “my_amazing_script”
  • $src – src komut dosyanızın konumudur. Plugins klasörümüzün uygun URL’sini almak için plugins_url fonksiyonunu kullanıyoruz. WordPress bunu bulduğunda, bu klasörde amazing_script.js dosya adımızı arayacaktır.
  • $deps – deps bağımlılık içindir. Scriptimiz jQuery kullandığı için bağımlılık alanına jQuery’yi ekledik. WordPress, sitede zaten yüklü değilse jQuery’yi otomatik olarak yükleyecektir.
  • $ver – Bu, kodumuzun sürüm numarasıdır. Bu parametre gerekli değildir.
  • $in_footer – Kodumuzu altbilgiye yüklemek istiyoruz, bu yüzden değeri true olarak ayarladık. Eğer betiği üstbilgiye yüklemek istiyorsanız, o zaman değeri false yaparsınız.

Tüm parametreleri wp_register_script içinde sağladıktan sonra, her şeyin gerçekleşmesini sağlayan wp_enqueue_script() içinde betiği çağırabiliriz.

Son adım, komut dosyasını gerçekten yüklemek için wp_enqueue_scripts eylem kancasını kullanmaktır. Bu bir örnek kod olduğu için, bunu diğer her şeyin hemen altına ekledik.

Bunu temanıza veya eklentinize ekliyorsanız, bu eylem kancasını komut dosyasının gerçekten gerekli olduğu yere yerleştirebilirsiniz. Bu, eklentinizin bellek ayak izini azaltmanıza olanak tanır.

Şimdi bazıları neden önce komut dosyasını kaydetmek ve sonra sıraya koymak için fazladan bir adım attığımızı merak edebilir? Bu, diğer site sahiplerinin eklentinizin çekirdek kodunu değiştirmeden komut dosyanızın kaydını silmelerine olanak tanır.

WordPress’te Stilleri Doğru Şekilde Sıraya Koyma

Tıpkı komut dosyaları gibi, stil sayfalarınızı da enqueue edebilirsiniz. Aşağıdaki örneğe bakın:

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

Stil sayfamızı eklemek için wp_enqueue_script kullanmak yerine artık wp_enqueue_style kullanıyoruz.

Hem stiller hem de komut dosyaları için wp_enqueue_scripts eylem kancasını kullandığımıza dikkat edin. İsmine rağmen, bu fonksiyon her ikisi için de çalışır.

Yukarıdaki örneklerde, enqueue etmek istediğimiz script veya stilin konumuna işaret etmek için plugins_url fonksiyonunu kullandık.

Ancak, temanızda enqueue scripts işlevini kullanıyorsanız, bunun yerine get_template_directory_uri() işlevini kullanmanız yeterlidir. Bir alt tema ile çalışıyorsanız get_stylesheet_directory_uri() işlevini kullanın.

Aşağıda örnek bir kod bulunmaktadır:

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

Umarız bu makale WordPress’te JavaScript ve stillerin nasıl düzgün bir şekilde ekleneceğini öğrenmenize yardımcı olmuştur. Gerçek hayattan bazı kod örnekleri için en iyi WordPress eklentilerinin kaynak kodunu incelemek veya WordPress yazılarına veya sayfalarına nasıl kolayca JavaScript ekleneceğine ilişkin kılavuzumuza göz atmak da isteyebilirsiniz.

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.

Açıklama: İçeriğimiz okuyucu desteklidir. Bu, bazı bağlantılarımıza tıklarsanız komisyon kazanabileceğimiz anlamına gelir. WPBeginner'ın nasıl finanse edildiğini, neden önemli olduğunu ve nasıl destek olabileceğinizi görün. İşte editoryal sürecimiz.

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.

Ultimate WordPress Araç Kiti

Araç setimize ÜCRETSİZ erişim sağlayın - her profesyonelin sahip olması gereken WordPress ile ilgili ürün ve kaynaklardan oluşan bir koleksiyon!

Reader Interactions

36 yorumBir Cevap Bırakın

  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.

      Yönetici

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

      Yönetici

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

Bir Cevap Bırakın

Yorum bırakmayı seçtiğiniz için teşekkür ederiz. Lütfen tüm yorumların yorum poli̇ti̇kasi uyarınca denetlendiğini ve e-posta adresinizin yayımlanmayacağını unutmayın. Ad alanında anahtar kelime KULLANMAYIN. Kişisel ve anlamlı bir sohbet edelim.