You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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_route setup. 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_LibraryIndex directly. If there's no data here, that's the root issue!
  • Check the $wpdb reference: You must declare global $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.php file 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:26:43