Wordpress Plugin Calling Database Results via AJAX

陌路散爱 提交于 2019-12-08 03:53:01

问题


I have written a Wordpress plugin which generates content for a page, then tries to call Update.php via jQuery.load to refresh the results. For example:

Plugin generates this content:

global $wpdb;
$sql = "SELECT * FROM table ORDER BY id;";
$results = $wpdb->get_results($sql);
<div id="content">Database Results Here Via Loop</div>

jQuery calls Update.php:

<script type="text/javascript">
$(function() {
  var refresh = setInterval(function() {
    $("#content").load("Update.php");
  }, 5000);
});

Update.php contains:

<?php
function update_page() {
  global $wpdb;
  $sql = "SELECT * FROM table ORDER BY id;";
  $results = $wpdb->get_results($sql);
  echo "Parsed results go here";
}
update_page();
?>

After 5 seconds, this results in a 'Fatal error: Call to a member function get_results() on a non-object' on the main page.

If I simply make Update.php return something like rand(), then it works fine and updates the div with a random number. However, if I attempt to include the header that defines all the Wordpress classes (i.e. $wpdb) in the Update.php file (e.g. require_once("wp-blog-header.php");) then the AJAX simply stops working altogether, and won't even return a rand(), yet it will prevent the fatal error mentioned above from occurring.

I am completely lost. Any help or just pointing me in the right direction would be greatly appreciated. Thank you in advance, kind sirs.


回答1:


you are calling update.php file using ajax so wordpress is unable to load other its files so it is not finding $wpdb objects definition so you need to do is require_once the wp-config.php and wp-includes/wp-db.php files

and create an object as $wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);

before the function update_page();




回答2:


ADD THIS LINE on Update.php file
require_once('../../../wp-load.php');

function update_page() {
global $wpdb;
$sql = "SELECT * FROM table ORDER BY id;";
$results = $wpdb->get_results($sql);
echo "Parsed results go here";
}
update_page();


来源:https://stackoverflow.com/questions/5410806/wordpress-plugin-calling-database-results-via-ajax

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