How can I initialize wpdb class in a php file?

ぐ巨炮叔叔 提交于 2019-12-13 15:23:11

问题


i am new in wordpress. i want to run a sql from a php file and this file is calling from a plugin file. my plugin file code is:

if (confirm('Are You Sure You Want to Delete?')){ 
window.location.href = '../wp-content/plugins/delete_data.php?id=<?php echo $db_data['dynamicmenu_id']; ?>';
} else{
}

and this code is running from script. my delete_data.php file code is given below:

dlt_opt();
function dlt_opt(){
    global $wpdb;
    var_dump($wpdb);
    $dlt_id = $_GET['id'];
    $result = $wpdb->query( $wpdb->prepare( "DELETE FROM ".$wpdb->prefix."dynamicmenu WHERE dynamicmenu_id=".$dlt_id ) );
}

but in delete_data.php is creating error because it is not finding $wpdb and is null. So wpdb is not initializing and it can't find wpdb class. how can i add wpdb class? Error message is:

Fatal error: Call to a member function query() on a non-object in ...\htdocs\wordpress\wp-content\plugins\delete_data.php on line 7

Need help


回答1:


Better to use require_once(ABSPATH . '/wp-load.php');




回答2:


I found my own answer. I need to include wp-load.php in that file.

require_once('../../wp-load.php');

although it's not a good practice to delete like this.



来源:https://stackoverflow.com/questions/8804589/how-can-i-initialize-wpdb-class-in-a-php-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!