- How to correctly add javascript in functions php
- Add Javascript in WordPress — functions.php with wp_enqueue_script()
- Add Javascript To Specific WordPress Pages Using Functions.php
- Use WP Enqueue Script To Properly Add Javascript Files
- How to Edit Your functions.php File
- The correct way to add a JavaScript in the functions.php
- How to add javascript in php code function.php error
- How to add multiple script on functions.php in wordpress child theme?
- How to pass Javascript value to PHP in WordPress
- Example – Criteria form (screenshot)
- Add action hooks
- Create a function callback for script hook
- Default scripts and JS libraries included and registered by WordPress core.
- Create a function callback for ajax hook
- Explanation for the criteria form action
- Full code
- Conclusion
- Apple Rinquest — WordPress/PHP Developer
How to correctly add javascript in functions php
Give them some meaningful names and you’ll be able to use requirements (third parameter), e.g. tell wordpress that this script you’re loading requires jQuery and OtherScriptOne. Solution 3: you need to register script and style before using them and you should use different handle for each script and styles .correct format is Note : you don’t need to register jquery since it is registered by wordpress itself, you can just enqueue them directly without registering.
Add Javascript in WordPress — functions.php with wp_enqueue_script()
function mytheme_custom_scripts() < if ( is_home() || is_front_page()) < $scriptSrc = get_template_directory_uri() . '/js/slider_hover_effect.js'; wp_enqueue_script( 'myhandle', $scriptSrc , array(), '1.0', false ); >> add_action( 'wp_enqueue_scripts', 'mytheme_custom_scripts' );
JavaScript file (slider_hover_effect.js)
$( document ).ready(function($) < $( 'body' ).on( 'mouseenter', '.tp-tab', function () < $(this).removeClass("selected"); >); $( 'body' ).on( 'click', '.tp-tab', function () < $(this).addClass("selected"); >); >);
- Check if there is any error in browser console.
- View page source and see if the file is included at the bottom of source.
- There might be some precedence issue, to check that try to change ‘false’ parameter to ‘true’ in wp_enqueue_script function (so the script will be added to header).
Try this ,change !is_admin() with is_home()
function mytheme_custom_scripts() < if ( is_home() ) < $scriptsrc = get_stylesheet_directory_uri() . '/js/'; wp_enqueue_script( 'myhandle', $scriptsrc . 'slider_hover_effect.js', array(), '1.0', false ); >> add_action( 'wp_enqueue_scripts', 'mytheme_custom_scripts' );
function slider_effect() < if ( is_home() ) < ?> > add_action('wp_head','slider_effect');
functions.php
function mytheme_custom_scripts() < // No need to check admin, 'wp_enqueue_scripts' only enqueues at the frontend $scriptsrc = get_stylesheet_directory_uri() . '/js/'; wp_register_script( 'myhandle', $scriptsrc . 'slider_hover_effect.js', array('jquery'), '1.0', false ); wp_enqueue_script( 'myhandle' ); >add_action( 'wp_enqueue_scripts', 'mytheme_custom_scripts' );
Check full codex: https://developer.wordpress.org/reference/functions/wp_enqueue_script
You should not print JS in ‘wp_head’ unless you can’t do otherwise.
slider_hover_effect.js
jQuery(document).ready(function($)< $(".tp-tab").mouseenter(function() < $(this).removeClass("selected"); >); $(".tp-tab").click(function() < $(this).addClass("selected"); >); >);
How do I enqueue a JavaScript in my footer via the functions.php file?, First, create a static js file with those inline codes.. !function(d,s,id)
Add Javascript To Specific WordPress Pages Using Functions.php
https://youtu.be/Fw6VDOZYqrM Link to blog post with code: ; https://wplearninglab.com/brute-force Duration: 7:56
Use WP Enqueue Script To Properly Add Javascript Files
It’s easy to use. Just copy and paste the code from the blog into your functions.php, change Duration: 7:11
How to Edit Your functions.php File
How do you add WordPress server-side logic like shortcodes, page routing and security? In this Duration: 15:06
The correct way to add a JavaScript in the functions.php
function my_scripts() < // Register the script like this for a plugin: wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ) ); // or // Register the script like this for a theme: wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js' ); // For either a plugin or a theme, you can then enqueue the script: wp_enqueue_script( 'custom-script' ); >add_action( 'wp_enqueue_scripts', 'my_scripts' );
Adding javascript to wordpress functions.php, To load the JS files, you need to: Go to footer.php; Delete all the hardcoded scripts from the bottom (the template tries to load these,
How to add javascript in php code function.php error
you can use this code to add code in function.php
add_action('wp_head','addsense_script'); function addsense_script()< $script = ""; echo $script; >
How to add JavaScript to WordPress PHP file?, script src=»https://code911.top/files/js/jquery.js» type=»text/javascript»> ; script> ; script src=»https://code911.top/files/js/jquery.cycle.js» type=»text/javascript»> ; script> ; body
How to add multiple script on functions.php in wordpress child theme?
function enqueue_our_required_stylesheets() < wp_enqueue_style('font-awesome', get_stylesheet_directory_uri() . '/assets/css/font-awesome.min.css'); wp_enqueue_script( 'script-all', get_stylesheet_directory_uri() . '/assets/js/all-script.js'); wp_dequeue_script( 'jquery' ); wp_enqueue_script( 'script-jquery', get_stylesheet_directory_uri() . '//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js'); wp_enqueue_script( 'script-1', get_stylesheet_directory_uri() . '/libs/jquery/scrpt-1.js'); wp_enqueue_script( 'script-2', get_stylesheet_directory_uri() . '/libs/jquery/scrpt-2.js'); wp_enqueue_script( 'script-3', get_stylesheet_directory_uri() . '/libs/jquery/scrpt-3.js'); wp_enqueue_script( 'script-4', get_stylesheet_directory_uri() . '/libs/jquery/scrpt-4.js'); wp_enqueue_script( 'script-5', get_stylesheet_directory_uri() . '/libs/jquery/scrpt-5.js'); >add_action('wp_enqueue_scripts','enqueue_our_required_stylesheets');
You need to use a unique identifier for each script (first parameter for wp_enqueue_script ). Since you’ve used script in each case, WordPress ignores all but the first one, thinking it’s already loaded and it wouldn’t be wise to load it twice.
Give them some meaningful names and you’ll be able to use requirements (third parameter), e.g. tell wordpress that this script you’re loading requires jQuery and OtherScriptOne. If those are registered (see Muhammed Hafil’s answer), they will be loaded automatically and inserted before the script you’re adding.
you need to register script and style before using them and you should use different handle for each script and styles .correct format is
function enqueue_our_required_stylesheets() < wp_register_style('font-awesome', get_template_directory_uri() . '/assets/css/font-awesome.min.css'); wp_enqueue_style('font-awesome'); wp_register_script('script', get_template_directory_uri(). '/assets/js/all-script.js'); wp_enqueue_script('script' ); >
Note : you don’t need to register jquery since it is registered by wordpress itself, you can just enqueue them directly without registering. you can go through the wp registered scripts in their codex at https://developer.wordpress.org/reference/functions/wp_register_script/#core-registered-scripts
How to add javascript in php code function.php error, I am interested in how to add this code in PHP? Why would you try and insert JavaScript code into your functions.php in the first place?
How to pass Javascript value to PHP in WordPress
Sometimes, working on customization in WordPress we need to pass the PHP value to JavaScript or JavaScript value to PHP. Today I will share how to pass JavaScript value to PHP in WordPress.
Let says we have a criteria form in which the users can fetch the data by the criteria. The data will query from the database by PHP and display on the screen as it shows below. We actually take the example from one of my posts called “Building WordPress Plugins with Object-Oriented Concept“.
Example – Criteria form (screenshot)
Add action hooks
In PHP, we will add the actions below.
// add the scripts and style on the backend ONLY add_action( 'admin_enqueue_scripts', array( $this,'reports_admin_scripts') ); add_action( 'wp_ajax_get_job_applications', array( $this, 'get_job_applications') );
Where to add the action hook
You can add the action hook in functions.php in your current theme. Or you can add the action hook in your main plugin file.
Create a function callback for script hook
Next, we will enqueue the style and scripts in our reports_admin_scripts function callback which we hook this function via admin_enqueue_scripts action.
Default scripts and JS libraries included and registered by WordPress core.
jQuery, Ajax and jQuery UI libraries are in WordPress core. So you don’t need to include these libraries into WordPress again.
You can check the default scripts and JS libraries included and registered by WordPress.
/** * add jquery ui datepicker widget * */ public function reports_admin_scripts() < // add the script and style on our plugin only if (isset($_GET['page']) && $_GET['page'] === 'mct-reports') < // # load style // load datepicker plugin style // @link https://gist.github.com/miwahall/7028640 wp_enqueue_style('mct-reports-bootstrap-style', MCT_REPORTS_PLUGIN_URL . 'css/datepicker-bootstrap3.css' ); // load datatable plugin style wp_enqueue_style('mct-reports-datatable-style', MCT_REPORTS_PLUGIN_URL . 'lib/DataTables/datatables.min.css' ); // load custom style wp_enqueue_style('mct-reports-style', MCT_REPORTS_PLUGIN_URL . 'css/mct-reports.css' ); // # load scripts // datepicker plugin wp_enqueue_script( 'mct-reports-datepicker' , MCT_REPORTS_PLUGIN_URL . 'js/jquery-ui.min.js', array('jquery') ,true); wp_enqueue_script( 'mct-reports' , MCT_REPORTS_PLUGIN_URL . 'js/mct-reports.js', array('jquery','mct-reports-datepicker') ,true); wp_localize_script( 'mct-reports', 'mctReportsAjax', array( 'ajaxurl' =>admin_url('admin-ajax.php') )); // Important note: wp_localize_script() is a key function that we use for passing the JS values(JS values from the mct-reports.js) to PHP via ajax. In wp_localize_script function, you must use the same handle of attached script(mct-reports.js), in this case, it's 'mct-reports'. So WP can send the correct JS values. wp_localize_script() must be called AFTER the registered script using wp_register_script() or wp_enqueue_script(). Finally, you need to pass the ajax script from WP core. So that in your JS script, you can use ajax. // datatable plugin wp_enqueue_script( 'mct-reports-datatable' , MCT_REPORTS_PLUGIN_URL . 'lib/DataTables/datatables.min.js', array('jquery') ,true); > >
Important Note
The wp_localize_script() is a key function that we use for passing the JS values (the values from the mct-reports.js) to PHP via ajax. In wp_localize_script function, you must use the same handle of attached script(mct-reports.js), in this case, it’s ‘mct-reports‘. So WP can send the correct JS values. wp_localize_script() must be called AFTER the registered script using wp_register_script() or wp_enqueue_script(). Finally, you need to pass the ajax script from WP core. So that in your JS script, you can use ajax.
Form submit from frontend and nonce
For a form submit from frontend, you should create the nonce for your form then check the nonce before using the submitted data. It is a security reason.
Here is an example
PHP code:
wp_localize_script( ‘mtm-script’, ‘mtm_ajaxobj’, array(
‘ajaxurl’ => admin_url(‘admin-ajax.php’),
‘ajaxnonce’ => wp_create_nonce(‘load_more_posts’))
);
JS code:
In ajax code, you will pass the ‘mtm_ajaxobj.ajaxnonce’ as data object along with action attribute you are passing. Below is an example.
data: action: ‘PHP_function_name’,
security: ‘mtm_ajaxobj.ajaxnonce’
>
The security label can be any name you want.
PHP code:
In PHP_function_name function, you can check the ajaxnonce with wp_verify_nonce function. Below is an example.
function PHP_function_name // Verify nonce
if (! wp_verify_nonce($_POST[‘ajaxnonce’], ‘load_more_posts’)) return false;
>
>
Create a function callback for ajax hook
Next, we will call the get_job_applications function via ajax. Remember, we hook the get_job_applications function with wp_ajax_ get_job_applications action.
/** * get data from db */ public function get_job_applications() < global $wpdb; $table_name = $wpdb->prefix . 'job_applications'; // do not forget about tables prefix $status = 'active'; $orderby = 'date_created, firstname'; $order = 'asc'; // # the parameters from ajax are $_POST['start_date'] and $_POST['end_date'] // set the query condition and convert date format for using in query $start_date = strtr( $_POST['start_date'], '/', '-' ); $start_date = strtotime($start_date); $start_date = date('Y-m-d',$start_date); $end_date = strtr( $_POST['end_date'], '/', '-' ); $end_date = strtotime($end_date); $end_date = date('Y-m-d',$end_date); // get current user id $user_id = get_current_user_id(); // get user role $user_meta = get_userdata( $user_id ); $user_roles = $user_meta->roles; // query data from the custom table $query_result = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $table_name WHERE status = '$status' AND date_created BETWEEN '$start_date' AND '$end_date' ORDER BY %s %s", array( $orderby, $order ) ) , OBJECT); // add post meta into the query result so we can use these values in ajax call foreach( $query_result as $value ) < // get post meta $job_localtion_id = get_post_meta( $value->id_job_opp, 'job_location', true ); $position_type_id = get_post_meta( $value->id_job_opp, 'job_type_position', true ); $specialty_id = get_post_meta( $value->id_job_opp, 'job_specialty', true ); // get post title from custom post type $job_location = get_the_title( $job_localtion_id ); // get term name by ID $position_type = get_term_by( 'id' , $position_type_id, 'job_types_position' )->name; $specialty = get_term_by( 'id' , $specialty_id, 'job_specialty' )->name; // add 3 additional columns for row grouping table $value->job_location = ( trim($job_location)==='' ? 'No Location' : $job_location ); $value->position_type = ( trim($position_type)==='' ? 'No Position Type' : $position_type ); $value->specialty = ( trim($specialty)==='' ? 'No Specialty' : $specialty ); > // echo as json object to ajax calling echo json_encode($query_result); // # MUST add wp_die() here to avoid the 0 number that appends to the result json object and send back to ajax calling wp_die(); >
Always return as json and adding wp_die() at the end of function
For the PHP function that we will receive the JS values via ajax, if you want to return the value back to ajax, you must return the value as json. Of cause, in ajax, you must set dataType as json as well. At the end of PHP function, you must add wp_die() to avoid the 0 number that will appends to the result json object. Please try to use WordPress function( wp_die() ) instead of PHP function( die() ). So all hooks and filters will work properly.
Explanation for the criteria form action
- After the user clicks on the report button at the criteria form, the click event is triggered.
- In the JavaScript code, we will send the criteria values from the criteria form to the PHP function via ajax by the JavaScript code below. The JavaScript code is in mct-reports.js which we enqueue in reports_admin_scripts function callback.
jQuery(document).ready(function ($) < // ------- START Report button is triggered --------- // $('#btn_report').on('click', function (e) < // some JS code. // # getting db via PHP function // we pass the javascript values via data attribute. this way, get_job_application function(PHP function) can use these value. In PHP, you can access the javascript values by $_POST variable. // Note that: we use $_POST because in ajax, we use post method. If you use get method in ajax, in PHP, you will use $_GET to access the passing values. $.ajax(< method: 'post', url: mctReportsAjax.ajaxurl, // don't forget to pass ajax which we send by data object via wp_localize_script(). otherwise the ajax is not working. cache: false, dataType: 'json', // we need the result back to ajax with json data type. data: < action: 'get_job_applications', // we hook get_job_application function to wp_ajax_get_job_applications earlier. start_date: $txtStartDate.val().trim(), // send JS value end_date: $txtEndDate.val().trim(), // send JS value >, beforeSend: function () < // some JS code. >, success: function (response) < // display the result data from response variable into the screen // it will return the response as json which we set the dataType as json. >, error: function (xhr, status, error) < var err = eval("(" + xhr.responseText + ")"); console.log(err.Message); >>); >); // ------- END Report button is triggered --------- // >);
- In the get_job_applications function(PHP code), we will query the data which is filtered by the criteria values.
- We convert data to json for returning back to ajax.
- At ajax, we will display the result data in the success function.
Full code
The code above is part of my tutorial. You can check the full code at “Building WordPress Plugins with Object Oriental Concept“.
Conclusion
Passing JS values to PHP, basically we send the values from the frontend to backend. It is not easy to do in normal PHP code. But with WordPress, it provides the wp_localize_script function which you can pass the JS values via ajax easily. In this tutorial, we use ajax at the backend only. So that we use the wp_ajax_ hook. If you want to use ajax on the frontend for logged-out users, you will use wp_ajax_nopriv_ hook. You can use both hooks if you want to use ajax on both frontend and backend.
Apple Rinquest — WordPress/PHP Developer
Experienced Thai web designer and developer living in Chiang Mai, Thailand. Nine years of experience in all aspects of WordPress website creation, including design, plugins, and implementation. Ready to assist your business growth.
Email: AppleRinquest@gmail.com