Reputation: 169
I'm trying to build my first WordPress plugin, and have admin menu labels already created using the add_menu_page() and content with a callable function in my functions.php file. For the life of me, I can't seem to add any javascript functions, or link to an external php page in the same plugin directory.
Has anyone else been able to do this?
Thanks!
Here's a code example. The code is a bit clunky, and I was wondering if there's a way to improve this/
function mt_sublevel_page() {
echo "<h2>" . __( 'Welcome', 'menu-test' ) . "</h2>";
echo '<div class="wrap">';
echo '<input type="button" value="Text Button" onclick="demo()" style="background-color:blue;">';
echo '</div>';
echo '<p class="test"></p>';
echo '<script>';
echo 'function demo() {var x = "Hello";document.getElementId("test").innerHTML=x;}';
echo '<script>';
}
Upvotes: 0
Views: 277
Reputation: 13840
This is typically how I load in a "mark-up" file for an admin page:
First of all, register your admin page function to the admin_menu
hook:
// Standard PHP Structure:
add_action( 'admin_menu', 'register_admin_page' );
// Using a Class Based structure
add_action( 'admin_menu', [$this, 'register_admin_page'] );
And then define your admin page function:
// Standard PHP Structure
function register_admin_page(){
add_menu_page( 'My Plugin', 'My Plugin', 'edit_posts', 'my-plugin', 'admin_markup', 'some-dashicon' );
}
// Class Based PHP Structure
public function register_admin_page(){
add_menu_page( 'My Plugin', 'My Plugin', 'edit_posts', 'my-plugin', [$this, 'admin_markup'], 'some-dashicon' );
}
Now, you can define your admin_markup
function:
function admin_markup(){
require_once dirname(__FILE__).'/admin-markup.php';
}
This leads you to something like this:
add_action( 'admin_menu', 'register_admin_page' );
function register_admin_page(){
add_menu_page( 'My Plugin', 'My Plugin', 'edit_posts', 'my-plugin', 'admin_markup', 'some-dashicon' );
}
function admin_markup(){
require_once dirname(__FILE__).'/admin-markup.php';
}
Now, inside your admin-markup.php
file, you can make use of the admin_enqueue_scripts()
function to load in scripts and styles to style the page as you wish.
Upvotes: 1