How to add custom javascript to Wordpress Admin using a plugin - wordpress

I am setting up a new Wordpress plugin with a custom metabox. This box contains sets of fields that I store in an array. I want the user to be able to add a new set of fields by clicking a button on the admin-page.
I read different posts on how to accomplish this but I havent succeeded yet. For testing purposes I created a real simple setup in the metabox to change a text of a element. This is also not working so I think it is a problem with loading the scripts correctly.
So what I did so far:
- add action through admin_enqueue_scripts
- register the script using wp_register_script
- enqueue script using wp_enqueue_script
- setup the js file (choose for testpurpose to store it in same dir as the plugin
function amai_woordjes_scripts() {
wp_register_script( 'amai_woordjes_updaten', 'amai_woordjes_updaten.js', array( 'jquery' ), '1.0', true );
wp_enqueue_script( 'amai_woordjes_updaten' );
}
add_action( 'admin_enqueue_scripts', 'amai_woordjes_scripts' );
//HTML code I use in the function which is called by add_meta_box
echo '<p id="demo">Current text</p>';
echo '<button id="woordje_toevoegen" onclick="woordjesToevoegen();">Woorden toevoegen</button>';
//amai_woordjes_updaten.js
<script>
function woordjesToevoegen() {
document.getElementById("demo").innerHTML = "New texxt";
}
</script>

You need use function wp_enque_script(). You use incorrect script path.
plugin_dir_path( __DIR__ ) . path/to/script.js

First You have to set the file path
Create js folder in your plugin root directory and move the 'amai_woordjes_updaten.js' file in js folder
function amai_woordjes_scripts() {
wp_register_script( 'amai_woordjes_updaten', plugin_dir_url( __FILE__ ).'js/amai_woordjes_updaten.js', array( 'jquery' ), '1.0', true );
wp_enqueue_script( 'amai_woordjes_updaten' );
}
add_action( 'admin_enqueue_scripts', 'amai_woordjes_scripts' );

Related

Plugin with shortcode, missing .js and .css files when used in widget areas

I'm working on a WordPress plugin which works perfectly if I insert the shortcode in a page or an article, but if I insert the shortcode in a widget area the .js and .css files aren't loaded.
//CUSTOM JS FUNCTIONS
add_action( 'wp_enqueue_scripts', 'my_functions' );
function my_functions() {
wp_register_script( 'my-script-1', plugin_dir_url( __FILE__ ) . 'js/functions.js', array( 'jquery' ), '1.0', true );
}
//CUSTOM CSS
add_action( 'wp_enqueue_scripts', 'my_css' );
function my_css() {
wp_register_style('my-css', plugin_dir_url( __FILE__ ) . 'css/style.css' );
}
//INCLUDE JS IF SHORTCODE EXIST
add_action( 'wp_print_styles', 'form_my_include' );
function form_my_include() {
global $post;
if (strstr($post->post_content, 'my_form_shortcode')) {
wp_enqueue_script('my-script-1');
wp_enqueue_style('my-css');
}
}
//SHORTCODE
function my_shortcode_add(){
ob_start();
include("include/my_function.php");
return ob_get_clean();
}
add_shortcode('my_shortcode', 'my_shortcode_add');
// Enable shortcodes in text widgets
add_filter('widget_text', 'do_shortcode');
You need to enqueue your script and stylesheet directly inside the shortcode. You can also load both the script and stylesheet inside the same wp_enqueue_scripts() hook.
//CUSTOM JS FUNCTIONS
add_action( 'wp_enqueue_scripts', 'my_scripts_and_stylesheets' );
function my_scripts_and_stylesheets() {
wp_register_script( 'my-script-1', plugin_dir_url( __FILE__ ) . 'js/functions.js', array( 'jquery' ), '1.0', true );
wp_register_style('my-css', plugin_dir_url( __FILE__ ) . 'css/style.css' );
}
//SHORTCODE
function my_shortcode_add(){
wp_enqueue_script('my-script-1'); //loaded here
wp_enqueue_style('my-css'); //loaded here
ob_start();
include("include/my_function.php");
return ob_get_clean();
}
add_shortcode('my_shortcode', 'my_shortcode_add');
// Enable shortcodes in text widgets
add_filter('widget_text', 'do_shortcode');
Your current code grabs to content inside post, and checks for the shortcode in there. Depending on where your shortcode is called, it might not actually be present in the post content, despite being present on the page.
By adding the wp_enqueue_script() & wp_enqueue_style() to your shortcode function, it will enqueue your whenever your shortcode is present on a page, regardless of where on the page it is.
Add this code to your plugin.
// Enable shortcodes in text widgets
add_filter('widget_text','do_shortcode');
This code simply adds a new filter allowing shortcodes to run inside widget.

Why is my javascript file not found by wordpress? and why doesn't my javascript file refresh?

I added custom javascript to a wordpress theme through the wp_enqueue_script()
function.
I placed my file in theme-folder/js/my-javascript.js
But it would not be found by wordpress! I would see the script tag in the html source inserted by wordpress, but clicking on it would take me to a "not found page". I looked around everywhere to see if this was some caching issue. Turned off caching, still nothing.
Finally, I ended up placing my-javascript.js file in the root of theme-folder, instead of 'js' folder. And now my js file was being found and loading.
But now a new problem I don't understand.. I would edit my file and the changes wouldn't reflect! I would have to change the file name of my js file everytime I made a change, renaming the file in my enqueue script function as well...I just wanted to get this task done.
So why does this happen? The site is hosted on dreamhost, and I suspect they used a one-click installer. Does dreamhost do some sort of caching on its own? and that's why?
Am I dumb? or does wordpress somehow know that I hate it?
Edit:
This is how I'm loading the script and how I left it working, but why won't my script refresh when I make changes and why doesn't it work when I place it in theme's 'js' folder?
/* Add floater script */
function add_floater_div_script(){
/* wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), 1.1, true); */
if ( is_page(1208) ) {
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js', array('jquery'), '', true);
}
}
add_action( 'wp_enqueue_scripts', 'add_floater_div_script' );
Edit: Changed code from "array ( " to "array(" because someone thought this was a problem. I did a quick check myself and PHP is ok with this space so this does not explain the weird wordpress behaviour I'm trying to solve.
Yeah, caching gets really annoying, Though hard reloading should solve the prob but we can't expect client to do it everytime. And WordPress has added a way to take care of that :)
wp_enqueue_script accepts 4th parameter as version number...
https://developer.wordpress.org/reference/functions/wp_enqueue_script/
So just update version after each update...
For development, Just set it as time()... So that it is reloaded every single time and never cached...
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js', array('jquery'), time(), true);
Your code will look something like this...
/* Add floater script */
function add_floater_div_script(){
/* wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), 1.1, true); */
if ( is_page(1208) ) {
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js', array('jquery'), time(), true);
}
}
add_action( 'wp_enqueue_scripts', 'add_floater_div_script' );
BE SURE TO REMOVE time() FROM PRODUCTION VERSION.
Or your file will never be cached by browser... Just set the version of your theme after dev is complete, so that every new version gets JS updated.
Try by wrapping your enqueue action in a function that you'll call on after_setup_theme hook in your functions.php
<?php
add_action( 'after_setup_theme', 'yourtheme_theme_setup' );
if ( ! function_exists( 'yourtheme_theme_setup' ) ) {
function yourtheme_theme_setup() {
add_action( 'wp_enqueue_scripts', 'yourtheme_scripts' );
}
}
if ( ! function_exists( 'yourtheme_scripts' ) ) {
function yourtheme_scripts() {
if ( is_page( 1208 ) ) {
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js', array( 'jquery' ), '', true );
}
}
}
Also be sure you're on page with id of 1208 to see if the script is actually loaded (because of the conditional).
And do a hard refresh (Ctrl+Shift+R).
The most common issue I see is an error in how you're enqueueing the file. Can you post code in your functions.php file that's enqueuing the JS file? Always be sure to reference the codex and other developer materials as well: https://developer.wordpress.org/themes/basics/including-css-javascript/
For future reference, it should look something like this:
wp_enqueue_script( 'script', get_template_directory_uri() . '/js/my-javascript.js');
Edit: After OP posted their code I saw they have a space after array which is causing an error, here is the correct code:
function add_floater_div_script() {
if ( is_page( 1208 ) ) {
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js', array( 'jquery' ), '1.0.0', true );
}
}
add_action( 'wp_enqueue_scripts', 'add_floater_div_script' );
add_action('wp_enqueue_scripts', 'load_scripts', 12);
function load_scripts() {
wp_enqueue_script('filename', get_template_directory_uri() . '/js/filename.js', array(), '1.0.0', true );
}
This is the proper way to import js in wordpress..
An really easy way to prevent caching of loaded resource files like Javascript-files is to add an random value after the filename that is to be included like so:
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js' . '?' . rand(), array('jquery'), '', true);
The PHP function
rand()
generates a random number and is appended to the file name after a '?' as query string. This forces reloading of the file every time the webpage is loaded.
Of course dismiss it for the production version.
Sometimes the issue could be simple somewhere a duplicated declaration of the name of the enqueue_script.
wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/custom-floater-
8.js', array('jquery'), '', true);
...
wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/custom-floater-
8.js', array('jquery'), '', true);
Don't use twice the same name 'custom-script' for example. The second will not be loaded.

Adding jquery to html5blank Wordpress

how do I actually add jQuery to html5blank wordpress theme by toddmotto?
I'm quite new to wordpress so I'm not really sure how does this work.
For normal html, I'll just link a script tag of jquery and another script tag with $(document).ready.. . . . . and start the jquery codes.
Would really love if someone who had experience using html5blank theme could shed some light.
Thanks much!
The WordPress recommends add jquery from WordPress itself.So you can add jquery using following way.
Add code to your current theme functions.php file.
function func_add_my_jquery() {
wp_enqueue_script( 'jquery' );
}
add_action( 'wp_enqueue_scripts', 'func_add_my_jquery' );
I load all my scripts from functions.php by using wp_enqeue_script. This will avoid duplicate loading.
If you only want to load Query, you can do this by:
function load_my_scripts() {
wp_enqueue_script( 'jquery' );
}
add_action( 'wp_enqueue_scripts', 'load_my_scripts' );
This will load the jQuery that follows WP. You can see other default scripts you can load here:
If you want to load other JS scripts, then you must use this:
function theme_name_scripts() {
wp_register_script( 'my-script', get_stylesheet_directory_uri() . '/js/my-script.js', array('jquery') );
wp_enqueue_script( 'my-script' );
}
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
The array('jquery') is for dependencies and in this case means that jQuery must be loaded before this script can be loaded.
If you want to register a newer version of jQuery, you first have to deregister the loaded jQuery:
wp_deregister_script( 'jquery' );

how to add javascript in wordpress template?

I want to add 2 js files in my wordpress template function-dir.php.
how to add this js file is there any tag?
is it right function to use
wp_register_script( $handle, $src, $deps, $ver, $in_footer );
Thanks in advance....
You use wp_register_script to register a script with its handle in order to avoid duplicating code (if for instance you enqueue it in several places and need to update the filename). This is usually not needed, I usually use wp_enqueue_script(), which takes the same arguments and outputs it to the page.
I usually do this by creating a setup function with all my style and script enqueues and then hooking that function up to one of the pre-made hooks, like this:
function theme_enqueue() {
/**
* Scripts.
*/
wp_enqueue_script('scripts', get_template_directory_uri() . '/js/lib/scripts.pkgd.min.js', array('jquery'), THEME_VERSION);
wp_enqueue_script('myscript', get_template_directory_uri() . '/js/myscript.js', array('scripts'), THEME_VERSION, TRUE);
wp_enqueue_script('main-menu', get_template_directory_uri() . '/js/menu.js', array('jquery'), THEME_VERSION, TRUE);
}
add_action('wp_enqueue_scripts','theme_enqueue');
You can use following structure as plugin by using wp_enqueue_script;
function add_custom_js() {
wp_enqueue_script( 'script_name', get_template_directory_uri() . '/js/custom.js', array(), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'add_custom_js' );
If you are developing plugin, you can add this action to your plugin. Or you can put this to functions.php
wp_register_script() function is used to register your script once and call anywhere, anytime. And wp_enqueue_script() is used to call it in your functions.php file
Method: 1
// First Register
function register_my_scripts(){
wp_register_script('handler_1', get_template_directory_uri() . "/js/script_one.js");
wp_register_script('handler_2', get_template_directory_uri() . "/js/script_two.js");
}
add_action('init', 'register_my_scripts');
Now use :
function wp24_load_script() {
// Check if you want to load for
// specific page
wp_enqueue_script('handler_1');
}
add_action("wp_enqueue_scirpts", "wp24_load_script");
Method: 2
Or you can directly load it with wp_enqueue_script() function:
function wp24_load_script() {
// Check if you want to load for
// specific page
wp_enqueue_script('handler_1', get_template_directory_uri() . "/js/script_one.js");
}
add_action("wp_enqueue_scirpts", "wp24_load_script");

Jplayer and wordpress 3.6.x

I am embedding my Jplayer code into my website however there is already jquery within the wordpress installation but when I copy my code across the player is broken as it shows no the volume icon with the x over it. When I include an external jquery script it breaks the entrie site but the player works. Is there any better way for me to include jPlayer into my wordpress site?
The jPlayer script enqueueing has to play by WordPress rules. The easiest (and maybe only) way is with a Shortcode. There are lot of developers, mainly Theme developers, that ignore that we don't dequeue the bundled jQuery version and load any version from some CDN (at least, we don't do it without knowing exactly what we're doing).
Here's a rough test, the shortcode callback function has to be polished a lot.
public function plugin_setup() // hooked into plugins_loaded
{
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
add_shortcode( 'jplayer', array( $this, 'shortcode' ) );
}
public function enqueue()
{
wp_register_script(
'sj-jplayer',
$this->plugin_url . 'js/jquery.jplayer.min.js',
array( 'jquery' ), // <------- Dependencies
false,
true
);
wp_register_style( 'sj-skin', $this->plugin_url . 'skin/blue.monday/jplayer.blue.monday.css' );
wp_enqueue_script( 'sj-jplayer' );
wp_enqueue_style( 'sj-skin' );
}
public function shortcode( $atts, $content )
{
ob_start();
require_once('html-shortcode.php');
$var = ob_get_clean();
return $var;
}
The file html-shortcode is basically this demo code adapted like:
<?php
/*
* Prints the shortcode
*/
?>
<script type="text/javascript">
jQuery(document).ready(function($) // <------ WP noConflict
{
$("#jquery_jplayer_1").jPlayer({});
});
</script>
<div id="jquery_jplayer_1" class="jp-jplayer"></div>
I tested this jPlayer shortcode inside another that does a jScrollPane, and it worked on the iPad.

Resources