Home > Software design >  WP functions undefined in plugin
WP functions undefined in plugin

Time:11-12

I am having trouble with a plugin I am writing, the plugin shows a form and the form submits to ajaxupload.php.

Basically in my plugin file:



add_action('plugins_loaded','add_to_menu');

function add_to_menu(){
    add_action('admin_menu', 'test_plugin_setup_menu');
}
 
function test_plugin_setup_menu(){
    add_menu_page( 'Test Plugin Page', 'add new entry', 'manage_options', 'test-plugin-link', 'test_init' );
    // ,'dashicons-database-add'
}
 
function test_init(){
    //echo "<h1>Hello World!</h1>";
    // do_action( 'admin_init' );

    include(ABSPATH."/wp-content/plugins/my-plugin/form.php");
    
    
}

In form.php I can call wp functions!

    <?php 
    // this works!
    echo wp_get_current_user()->user_login;
    ?>
    
    <form>
    ...
    </form>
    <script>
    $(document).ready(function(){
        $("#my_form").on("submit",function(e){
        e.preventDefault();
        var sendData = $( this ).serialize();
                $.ajax({
                    url: "../wp-content/plugins/my-plugin/ajaxupload.php",
                    type: "POST",
                    data:  new FormData(this),
        ...
       </script>

in Ajaxupload.php I can't use any WP constants or functions before submission...



if( !empty($_POST['imgurl']) || !empty($_FILES['image']) )
{
$someform_field = $_POST["name"];
echo wp_get_current_user()->user_login; //this line fails

//then call to wpdb to add data to DB 

What should be the correct sequence to make wp functions usable in the ajaxupload.php file?

CodePudding user response:

You have to load the wp-load.php file in your ajaxload.php, which loads all wordpress functions, because your ajaxload.php file is called directly:

<?php 
require_once __DIR__ . '/../../../wp-load.php';

$someform_field = $_POST["name"];
$user = wp_get_current_user()->user_login; // should now work

//then call to wpdb to add data to DB
  • Related