I have some code that have a button in the backend page.
I want to click on the button and have it activate a plugin that's already in the plugin's directory.
Here's the code:
<?php
add_action('admin_menu', 'addons_plugin_setup_menu');
function addons_plugin_setup_menu(){
add_menu_page( 'Addons', 'Addons', 'manage_options', 'addons-plugin', 'addons_init' );
}
function addons_init(){
?>
<div class="container-fluid" style="margin-top: 30px">
<div class="row">
<div class="col-md-12">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<h4>Addons</h4>
<br><br>
<button class="btn btn-success" onclick="testme()">Activate</button>
</div>
</div>
</nav>
</div>
</div>
</div>
<?php
}
function testme() {
activate_plugin( 'plugin-dir/plugin-file.php' );
if ( is_wp_error( $result ) ) {
// Process Error
}
}
?>
When I click the button I get "testme" is not defined
How can I get this to work?
Updated to this:
<?php
add_action('admin_menu', 'addons_plugin_setup_menu');
function addons_plugin_setup_menu(){
add_menu_page( 'Addons', 'Addons', 'manage_options', 'addons', 'addons_init' );
}
function addons_init(){
?>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
jQuery( document ).ready( function($) {
$( '#activate_plugin' ).on( 'click', function(e) {
e.preventDefault();
var ajaxurl = '<?php echo admin_url( "admin-ajax.php" ); ?>';
var security = '<?php echo wp_create_nonce( "activate_plugin" ); ?>';
$.ajax( {
url: ajaxurl,
dataType: 'json',
type: 'POST',
delay: 150,
data :'action=activate_plugin&security='+security,
success: function( data ) {
console.log( data + ', Plugin Activated!' );
},
} );
} );
} );
</script>
<div class="container-fluid" style="margin-top: 30px">
<div class="row">
<div class="col-md-12">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<h4>Addons</h4>
<br><br>
<button id="activate_plugin" class="btn btn-success">Activate</button>
</div>
</div>
</nav>
</div>
</div>
</div>
<?php
function activate_plugin_ajax_callback() {
check_ajax_referer( 'activate_plugin', 'security' );
activate_plugin( 'ttt/index.php' );
if( is_wp_error( $result ) ) {
// Process Error
}
}
add_action( 'wp_ajax_activate_plugin', 'activate_plugin_ajax_callback' );
?>
<?php
}
?>
onclick
. I think what you'd need to do is use AJAX to call thetestme()
function. I've never even attempted it before but if you do want to try it this way tryonclick="<?php testme(); ?>"
but I'm like 99.99% certain the won't work either.