WordPress自定义路由无法返回数据库数据问题求助
Hey Jake, let's break down how to troubleshoot this step by step—since you're new to WordPress, I'll keep things clear and actionable!
1. First, Verify Your Custom Endpoint Registration
Since your request isn't throwing a 404, the endpoint is reachable, but we need to make sure it's configured to return data properly.
- Double-check your
register_rest_routesetup. You must use WordPress's REST response functions instead of just returning an array or echoing content. For example:// Correct endpoint registration example add_action('rest_api_init', function() { register_rest_route( 'my-library/v1', // Your custom namespace '/index-data/', // Your endpoint route array( 'methods' => 'GET', 'callback' => 'fetch_library_index_data', 'permission_callback' => '__return_true', // Temp: allow all access for testing ) ); }); // Callback function with proper response handling function fetch_library_index_data() { global $wpdb; // Critical: access WordPress's database object $table_name = 'saic3_LibraryIndex'; // Use full table name if prefix isn't part of it // Run your query $results = $wpdb->get_results("SELECT * FROM $table_name"); // Check for database errors if ($wpdb->last_error) { return new WP_Error('db_query_failed', $wpdb->last_error, array('status' => 500)); } // Return valid REST response return rest_ensure_response($results); } - Make sure your Ajax request URL matches the endpoint path (e.g.,
wp-json/my-library/v1/index-data).
2. Validate Your Database Query
Empty results often come from a query that's not pulling data correctly:
- Confirm the table exists and has data: Log into phpMyAdmin (or your database tool) and run
SELECT * FROM saic3_LibraryIndexdirectly. If there's no data here, that's the root issue! - Check the
$wpdbreference: You must declareglobal $wpdb;in your callback function—without it, WordPress can't access the database. - Debug the query error: Add
var_dump($wpdb->last_error);inside your callback to see if the query is failing (enable WP_DEBUG to see this output).
3. Inspect Your Frontend Ajax Request
Use your browser's DevTools (F12 → Network tab) to dig into the request:
- Look at the Response and Preview tabs for the Ajax call. Is it returning an empty array, an error message, or nothing at all?
- Ensure your JS is handling the response correctly. Here's a solid example:
document.addEventListener('DOMContentLoaded', function() { fetch('/wp-json/my-library/v1/index-data') .then(response => { if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`); return response.json(); }) .then(data => { console.log('Fetched data:', data); // Check console for results first // Add your page-populating logic here }) .catch(error => console.error('Fetch failed:', error)); });
4. Enable WordPress Debug Mode
Turn on debugging to catch hidden errors:
- Open your
wp-config.phpfile and add these lines:define('WP_DEBUG', true); define('WP_DEBUG_LOG', true); - Errors will log to
wp-content/debug.log—this can reveal issues with your query or endpoint code that aren't showing up in the browser.
内容的提问来源于stack exchange,提问作者Jake
相关产品推荐
相关产品推荐

