Search code examples
wordpresswoocommercewordpress-rest-api

Wordpress API returning empty meta array


If you hit /wp-json/wp/v2/comments?post=X on a wordpress blog it returns JSON of comments for that post ID. I am able to get results without an issue, but the meta is an empty array instead of having any meta values related to the comment.

I also have tried visiting /wp-json/wp/v2/comments/X to pull an individual comment, but that is also returning an empty meta array.

There is a rating field saved in the wp_commentmeta table and I'm expecting this to be returned so that I can display reviews from woocommerce on a 3rd party site.


Solution

  • I found that WooCommerce itself has its own API which does return the meta value of rating, but they want an API key for something like fetching comments. I looked at the methods they use to build the response and they are just cycling through get_comments() results and then creating a new array with rating appended via doing get_comment_meta($commentid, 'rating')

    I cannot rely on an API key for what I need as this is meant to be publicly available for me, so I added an API endpoint /wp-json/wc/v2/reviews which now does what I need.

    add_action('rest_api_init', 'comments_api_endpoint');   
    function comments_api_endpoint()
    {           
        register_rest_route( 'wc/v2', '/reviews/', array(
            'methods' => ['GET'],
            'callback' => 'comments_api',
        ));
    }
    function comments_api()
    {
        $data = [];
        $reviews = get_approved_comments($_GET['id']);
        foreach($reviews as $review) {
            $data[] = [
                'author'  => $review->comment_author,
                'rating'  => get_comment_meta($review->comment_ID, 'rating', true),
                'content' => $review->comment_content
            ];
        }
        return $data;
    }