Tinuzzz
Tinuzzz

Reputation: 1

How to add custom javascript to Wordpress Admin using a plugin

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>

Upvotes: 0

Views: 2858

Answers (2)

gaurav sharma
gaurav sharma

Reputation: 544

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

Upvotes: 2

WP Punk
WP Punk

Reputation: 1444

You need use function wp_enque_script(). You use incorrect script path.

plugin_dir_path( __DIR__ ) . path/to/script.js

Upvotes: 2

Related Questions