fatal error: call to a member function delete() on a non-object wordpress

I am trying to delete rows from db and getting this error. I googled and tried all the possible solution still no luck. I also mentioned “global $wpdb” but dont know why getting this error.

<?php
if($_POST['array'])
{
    global $wpdb;
    $productArray = $_POST["array"];
    $count = count($productArray);
    $table_name = "wp_cause_woocommerce_product";

    for( $i=0; $i < $count; $i++ ){
        $wpdb->delete( $table_name, array( 'product_ID' => $productArray[$i] ), array( '%d' ) );
    }

}

Related posts

Leave a Reply

2 comments

  1. I think the issue is that you are not getting the WordPress functions.

    Add this in to the top of your code.

    define('WP_USE_THEMES', false); 
    require_once( $_SERVER['DOCUMENT_ROOT'] . '/fundraise/wp-load.php' );
    

    If you change your project path make sure you update the path to wp-load.php.

    If you will change your project path in future, you can try this

    define('WP_USE_THEMES', false); 
    require_once( dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/wp-load.php');
    

    Hope this helps.

  2. I just add the below lines on top of the page and its working. I had to relate the file with wp functionality thats it :

    define('WP_USE_THEMES', false);
    require_once( $_SERVER['DOCUMENT_ROOT'] . '/fundraise/wp-load.php' );