You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

WordPress自定义REST API端点未返回指定数据,求解决建议

Fixing Your WordPress Custom REST Endpoint Not Returning Callback Data

Let's break down what's going wrong here and how to fix it quickly.

The Core Issue: Incorrect register_rest_route Parameter Order

Looking at your code, you've mixed up the parameters for register_rest_route. The function expects three key arguments in this order:

  1. The namespace string
  2. A specific route path string (like /data or /test)
  3. The configuration array (methods, callback, etc.)

Your current code passes the configuration array as the second parameter instead of the third. This means WordPress is registering the root of your custom namespace (/custom) as the route—and by default, accessing that root URL returns a list of all routes in the namespace, which is exactly what you're seeing in your response.

Corrected Code

Here's the fixed version of your code:

add_action('rest_api_init', function(){
    // Correct parameter order: namespace, route path, config array
    register_rest_route(
        'custom', 
        '/data', // Add a specific path for your endpoint
        array(
            'methods' => 'GET',
            'callback' => 'return_custom_data',
        )
    );
});

function return_custom_data(){
    return 'test';
}

What Changed?

  • Added a specific route path (/data) as the second argument to register_rest_route
  • Moved your configuration array to the third parameter position, where it belongs

How to Test It

Now, access the endpoint at:
http://localhost/index.php/wp-json/custom/data

You should see the 'test' response you expected right away.

Additional Troubleshooting Tips

If it still doesn't work, check these common pitfalls:

  • Callback Function Spelling: Double-check that return_custom_data is spelled identically everywhere—typos are one of the most frequent causes of this issue.
  • Flush REST Routes: WordPress caches REST route definitions. Head to your WordPress admin → Settings → Permalinks, and just click "Save Changes" (no need to modify any settings) to flush the cache.
  • Permission Checks: For simple GET endpoints returning non-sensitive data, the default read permission works fine. If you later add sensitive data, you'll want to add a permission_callback to your config array to restrict access.

内容的提问来源于stack exchange,提问作者OhMad

火山引擎 最新活动