简体   繁体   中英

How to insert this javascript in wordpress functions

I'm trying to create this login/forward function on a wordpress site and I'm getting no results

The function works in jsfiddle, but putting it into wordpress just doesn't seem to work. Check: https://jsfiddle.net/theomw/vawc3t17/1/ for the code

I added this to the wordpress page:

<input type="text" id="token" name="token"/>
<input type="button" name="login" value="login" onClick="changeQuery()"/>

I added a .js file with this as content:

function changeQuery(){
    var input_query = document.getElementById('token').value;
    window.location = "https://www.example.com/" + input_query;

}

And this is my functions.php file (login funtion part is the code)

<?php
/*** Child Theme Function  ***/

/*** login Function  ***/
 function loginscript() {
 wp_enqueue_script('loginscript', get_stylesheet_directory_uri() . 
 '/loginscript.js');
 }
add_action('wp_head','loginscript');
 }

I don't get any error in the functions.php . But the code doesn't work. In the debug mode on chrome I get a few errors:

Uncheck runtime.lasterror: the messageport closed before a response was received.

I don't know if its related to the problem. Can someone push me in the right direction to solve this?

snapshot of error

First, try echoing the script in the wp_head to see if you can get it to work. If that works, it's likely that you have an issue with your file path in your wp_enqueue.

So try this, then load the page and see if it works. You should not add JS to your site this way generally, but is effective in testing . Enqueuing is the proper way to add scripts and styles, but in order to determine that it's not the JS, and is something else, you should try this.

function loginscript() {
    echo " 
    <script>
     function changeQuery(){
     var input_query = document.getElementById('token').value;
     window.location = 'https://www.example.com/' + input_query;
    </script> ";

  }
}
add_action('wp_head','loginscript');

If the functionality works this way, then check your file path. It might be easier to just use the full relative file path rather than using wordpress built in file path functions. So for example, if you js file has a path of /wp-content/themes/my-theme/js/loginscript.js, you could do an enqueue like so:

wp_enqueue_script('loginscript', '/wp-content/themes/theme_name/js/loginscript.js');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM