Programing

WordPress에 간단한 jQuery 스크립트를 어떻게 추가합니까?

crosscheck 2020. 7. 25. 10:33
반응형

WordPress에 간단한 jQuery 스크립트를 어떻게 추가합니까?


WordPress에서 jQuery를 사용하는 방법과 매우 실망스러운 Codex와 블로그 게시물을 읽었습니다. jQuery를 functions.php파일 로로드하는 것까지는 있지만 이미 많은 WordPress 경험이 있다고 가정하기 때문에 모든 가이드가 엉망입니다. 예를 들어, 그들은 functions.php파일을 통해 jQuery를로드하고 있다고 말합니다. 이제 jQuery를로드하면 됩니다.

정확히 어떻게해야합니까? 구체적으로 어떤 파일에 코드를 추가합니까? 단일 WordPress 페이지에 정확히 어떻게 추가합니까?


튜토리얼에 대한 당신의 의미를 알고 있습니다. 내가하는 방법은 다음과 같습니다.

먼저 스크립트를 작성해야합니다. 테마 폴더에 'js'와 같은 폴더를 만듭니다. 해당 폴더에 자바 스크립트 용 파일을 만듭니다. 예 : your-script.js. 해당 파일에 jQuery 스크립트를 추가하십시오 ( <script>.js 파일에는 태그가 필요하지 않습니다 ).

다음은 jQuery 스크립트 (wp-content / themes / your-theme / js / your-scrript.js)의 모양 예입니다.

jQuery(document).ready(function($) {
  $('#nav a').last().addClass('last');
})

함수 시작시 $가 아닌 jQuery를 사용합니다.

이제 테마의 functions.php 파일을여십시오. wp_enqueue_script()기능 을 사용 하여 스크립트를 추가하고 WordPress에 jQuery에 의존한다는 것을 알려줄 수 있습니다. 이를 수행하는 방법은 다음과 같습니다.

add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
    wp_enqueue_script(
        'your-script', // name your script so that you can attach other scripts and de-register, etc.
        get_template_directory_uri() . '/js/your-script.js', // this is the location of your script file
        array('jquery') // this array lists the scripts upon which your script depends
    );
}

테마에 올바른 위치에 wp_head 및 wp_footer가 있다고 가정하면 작동합니다. 도움이 더 필요하면 알려주십시오.

워드 프레스 질문은 워드 프레스 답변 에서 질문 할 수 있습니다 .


많은 검색 끝에 마침내 최신 WordPress에서 작동하는 것을 발견했습니다. 수행 할 단계는 다음과 같습니다.

  1. 테마의 디렉토리를 찾고 사용자 정의 js의 디렉토리에 폴더를 작성하십시오 ( 이 예제에서는 custom_js ).
  2. 이 디렉토리의 .js 파일에 사용자 정의 jQuery를 넣으십시오 ( 이 예제에서는 jquery_test.js ).
  3. 사용자 정의 jQuery .js가 다음과 같은지 확인하십시오.

    (function($) {
    $(document).ready(function() {
    $('.your-class').addClass('do-my-bidding');
    })
    })(jQuery);
    
  4. 테마의 디렉토리로 이동하여 functions.php를여십시오.

  5. 상단에 다음과 같은 코드를 추가하십시오.

    //this goes in functions.php near the top
    function my_scripts_method() {
    // register your script location, dependencies and version
       wp_register_script('custom_script',
       get_template_directory_uri() . '/custom_js/jquery_test.js',
       array('jquery'),
       '1.0' );
     // enqueue the script
      wp_enqueue_script('custom_script');
      }
    add_action('wp_enqueue_scripts', 'my_scripts_method');
    
  6. 사이트가 작동하는지 확인하십시오!

If you use wordpress child theme for add scripts to your theme, you should change the get_template_directory_uri function to get_stylesheet_directory_uri, for example :

Parent Theme :

add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
    wp_register_script(
        'parent-theme-script', 
        get_template_directory_uri() . '/js/your-script.js', 
        array('jquery') 
    );

    wp_enqueue_script('parent-theme-script');
}

Child Theme :

add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
    wp_register_script(
       'child-theme-script', 
       get_stylesheet_directory_uri() . '/js/your-script.js', 
       array('jquery') 
    );

    wp_enqueue_script('child-theme-script');
}

get_template_directory_uri : /your-site/wp-content/themes/parent-theme

get_stylesheet_directory_uri : /your-site/wp-content/themes/child-theme


You can add jQuery or javascript in theme's function.php file. The code is as below :

add_action( 'wp_enqueue_scripts', 'add_my_script' );

function add_my_script() {
wp_enqueue_script(
    'your_script_name', // your script unique name 
    get_template_directory_uri().'/js/your-script.js', //script file location
    array('jquery') //lists the scripts upon which your script depends
);
}

For more detail visit this tutorial : http://www.codecanal.com/add-simple-jquery-script-wordpress/


Beside putting the script in through functions you can "just" include a link ( a link rel tag that is) in the header, the footer, in any template, where ever. You just need to make sure the path is correct. I suggest using something like this (assuming you are in your theme's directory).

<script type="javascript" href="<?php echo get_template_directory_uri();?>/your-file.js"></script>

A good practice is to include this right before the closing body tag or at least just prior to your footer. You can also use php includes, or several other methods of pulling this file in.

<script type="javascript"><?php include('your-file.js');?></script>

**#Method 1:**Try to put your jquery code in a separate js file.

Now register that script in functions.php file.

function add_my_script() {
    wp_enqueue_script(
      'custom-script', get_template_directory_uri() . '/js/your-script-name.js', 
        array('jquery') 
    );
}
add_action( 'wp_enqueue_scripts', 'add_my_script' );

Now you are done.

Registering script in functions has it benefits as it comes in <head> section when page loads thus it is a part of header.php always. So you don't have to repeat your code each time you write a new html content.

#Method 2: put the script code inside the page body under <script> tag. Then you don't have to register it in functions.


You can add custom javascript or jquery using this plugin.
https://wordpress.org/plugins/custom-javascript-editor/

When you use jQuery don't forget use jquery noconflict mode


There are many tutorials and answers here how to add your script to be included in the page. But what I couldn't find is how to structure that code so it will work properly. This is due the $ being not used in this form of JQuery.

So here is my code and you can use that as a template.

jQuery(document).ready(function( $ ){
  $("#btnCalculate").click(function () {
        var val1 = $(".visits").val();
        var val2 = $(".collection").val();
        var val3 = $(".percent").val();
        var val4 = $(".expired").val();
        var val5 = $(".payer").val();
        var val6 = $(".deductible").val(); 
        var result = val1 * (val3 / 100) * 10 * 0.25;
        var result2 = val1 * val2 * (val4 / 100) * 0.2;
        var result3 = val1 * val2 * (val5 / 100) * 0.2;
        var result4 = val1 * val2 * (val6 / 100) * 0.1;
        var val7 = $(".pverify").val();
        var result5 = result + result2 + result3 + result4 - val7;
        var result6 = result5 * 12;
        $("#result").val("$" + result);
        $("#result2").val("$" + result2);
        $("#result3").val("$" + result3);
        $("#result4").val("$" + result4);
        $("#result5").val("$" + result5);
        $("#result6").val("$" + result6);
  });
});

Answer from here: https://premium.wpmudev.org/blog/adding-jquery-scripts-wordpress/

Despite the fact WordPress has been around for a while, and the method of adding scripts to themes and plugins has been the same for years, there is still some confusion around how exactly you’re supposed to add scripts. So let’s clear it up.

Since jQuery is still the most commonly used Javascript framework, let’s take a look at how you can add a simple script to your theme or plugin.

jQuery’s Compatibility Mode

Before we start attaching scripts to WordPress, let’s look at jQuery’s compatibility mode. WordPress comes pre-packaged with a copy of jQuery, which you should use with your code. When WordPress’ jQuery is loaded, it uses compatibility mode, which is a mechanism for avoiding conflicts with other language libraries.

What this boils down to is that you can’t use the dollar sign directly as you would in other projects. When writing jQuery for WordPress you need to use jQuery instead. Take a look at the code below to see what I mean:


You can use WordPress predefined function to add script file to WordPress plugin.

wp_enqueue_script( 'script', plugins_url('js/demo_script.js', __FILE__), array('jquery'));

Look at the post which helps you to understand that how easily you can implement jQuery and CSS in WordPress plugin.


"We have Google" cit. For properly use script inside wordpress just add hosted libraries. Like Google

After selected library that you need link it before your custom script: exmpl

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

and after your own script

<script type="text/javascript">
$(document).ready(function(){
    $('.text_container').addClass("hidden");</script>

Beside putting the script in through functions you can "just" include a link ( a link rel tag that is) in the header, the footer, in any template, where ever.

No. You should never just add a link to an external script like this in WordPress. Enqueuing them through the functions.php file ensures that scripts are loaded in the correct order.

Failure to enqueue them may result in your script not working, although it is written correctly.


you can write your script in another file.And enqueue your file like this suppose your script name is image-ticker.js.

wp_enqueue_script( 'image-ticker-1', plugins_url('/js/image-ticker.js', __FILE__), array('jquery', 'image-ticker'), '1.0.0', true ); 

in the place of /js/image-ticker.js you should put your js file path.


In WordPress, the correct way to include the scripts in your website is by using the following functions.

wp_register_script( $handle, $src )
wp_enqueue_script( $handle, $src )

These functions are called inside the hook wp_enqueue_script.

For more details and examples, you can check Adding JS files in Wordpress using wp_register_script & wp_enqueue_script

Example:

function webolute_theme_scripts() {
    wp_register_script( 'script-name', get_template_directory_uri() . '/js/example.js', array('jquery'), '1.0.0', true );
    wp_enqueue_script( 'script-name' );
}
add_action( 'wp_enqueue_scripts', 'webolute_theme_scripts' );

Do you only need to load jquery?

1) Like the other guides say, register your script in your functions.php file like so:

// register scripts
if (!is_admin()) {
    // here is an example of loading a custom script in a /scripts/ folder in your theme:
    wp_register_script('sandbox.common', get_bloginfo('template_url').'/scripts/common.js', array('jquery'), '1.0', true);
    // enqueue these scripts everywhere
    wp_enqueue_script('jquery');
    wp_enqueue_script('sandbox.common');
}

2) Notice that we don't need to register jQuery because it's already in the core. Make sure wp_footer() is called in your footer.php and wp_head() is called in your header.php (this is where it will output the script tag), and jQuery will load on every page. When you enqueue jQuery with WordPress it will be in "no conflict" mode, so you have to use jQuery instead of $. You can deregister jQuery if you want and re-register your own by doing wp_deregister_script('jquery').

참고URL : https://stackoverflow.com/questions/11159860/how-do-i-add-a-simple-jquery-script-to-wordpress

반응형