0

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?

1
  • What is the content of your ajaxupload.php file? Commented Nov 10, 2022 at 12:31

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Additionally, the page is accessed within the WordPress context only (from wp-admin) which means I should not need to load wp components manually...
Your page might be called within the wordpress context, but your jquery makes an direct ajax call of the ajaxload.php. So it cannot work without loading the core again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.