0
votes

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>';
}
1
With regard to the js, google "admin_enqueue_scripts". Not really sure what you mean by the second question about linking page contents to an external php file, but if I had to guess, this may help: stackoverflow.com/questions/13343761/… - git-e-up
Share your code and we might be able to help. - cabrerahector
Thanks for the response! That wasn't very clear so I edited my question. I meant adding a link to an external file in the same directory that contains the page markup. - PhysicsIsRelativelyCool

1 Answers

1
votes

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.