0

I am trying to use a custom WordPress route and function, but I am getting a route and function not found error. Below is my code but I am not sure where it is breaking:

add_action('rest_api_init', function () {
 register_rest_route( 'boss/v1/latest-quiz-results',array(
            'methods'  => 'GET',
            'callback' => 'get_latest_quiz_results'
  ));
});
function get_latest_quiz_results() {
 $query = $wpdb->prepare(
 "SELECT post_id, 
   5PxenC_learndash_user_activity_meta.activity_meta_key, 
   5PxenC_learndash_user_activity_meta.activity_meta_value, 
   5PxenC_learndash_user_activity.activity_id, user_id, course_id
  FROM 5PxenC_learndash_user_activity
 INNER JOIN 5PxenC_learndash_user_activity_meta ON 5PxenC_learndash_user_activity_meta.activity_id = 5PxenC_learndash_user_activity.activity_id
  WHERE 5PxenC_learndash_user_activity_meta.activity_meta_key = 'pass'");
$results = $wpdb->get_results($query);
if (empty($results)) {
return new WP_Error( 'empty_category', 'there is no quiz data', 
array('status' => 404) );

}

$response = new WP_REST_Response($results);
$response->set_status(200);

 return $results;
 }
  • Is that latest-quiz-results/) (the route) just a typo in the question? – Sally CJ Jan 22 at 22:52
  • @SallyCJ sorry, typo issue. now fixed – Joel Scalera Jan 22 at 23:22
  • Check my answer. I hope it helps you. – Sally CJ Jan 23 at 0:29
1

There are 3 issues with your code:

  1. The proper syntax of registering your custom REST API route, is as follows:

    register_rest_route( $namespace, $base_URL, $args, $override );
    

    So:

    register_rest_route( 'boss/v1', '/latest-quiz-results', array(
        'methods'  => 'GET',
        'callback' => 'get_latest_quiz_results'
    ) );
    

    Consult the reference for more information.

  2. In the get_latest_quiz_results(), $wpdb is not defined because you're missing global $wpdb; at the top:

    function get_latest_quiz_results() {
        global $wpdb; // Add this.
        ...
    
        return $results;
    }
    
  3. Also in get_latest_quiz_results(), you incorrectly called wpdb::prepare() — the second parameter is mandatory, and there needs to be at least one placeholder (e.g. %s). So for example:

    $query = $wpdb->prepare( "SELECT ... WHERE 5PxenC_learndash_user_activity_meta.activity_meta_key = %s", 'pass' );

  • You're welcome. :) – Sally CJ Jan 24 at 7:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.