首页 文章

如何在WordPress中将$ wpdb-> get_results作为json返回?

提问于
浏览
0

我在wordpress中创建了一个名为 custom_users 的自定义表,我想通过API访问记录

functions.php

function get_wp_custom_users()
{
    global $wpdb;

    $custom_users = $wpdb->get_results("SELECT * FROM wp_custom_users");

    foreach ($custom_users as $custom_user)
    {
        echo $custom_user->first_name.' '.$custom_user->last_name;
    }
}

add_action('rest_api_init', function()
{
    register_rest_route( 'wpcustomusers/v1', '/users/', array(
        'methods' => 'GET',
        'callback' => 'get_wp_custom_users'
    ));
});

API可以通过url http://localhost/mywebsite/wp-json/wpcustomusers/v1/users 访问

您知道如何从API请求中将 for loop 中的结果作为JSON返回?

我希望看到所有领域都归还..感谢您的帮助 .

2 回答

  • 1

    不需要 foreach 循环,进行如下更改 .

    function get_wp_custom_users(){
      global $wpdb;
    
      $custom_users = $wpdb->get_results("SELECT * FROM wp_custom_users");
    
      //change as below.
      echo json_encode($custom_users);
    }
    
  • 1

    var_dump $ custom_users以确保$ custom_users不为空 . 跳过 for loop . 将 return 替换为 echo .

    echo json_encode($custom_users);
    

相关问题