1

I'm developing a custom WooCommerce plugin that needs to extend the WooCommerce Store API. Specifically, I want to filter product reviews by the current author when viewing the author page. This is the current api output:

GET /wc/store/v1/products/reviews {"context":"view","page":1,"per_page":10,"order":"desc","orderby":"date_gmt","offset":0,"_locale":"user"}

My end goal is for the "All reviews" guttenberg block, when added to the author page, to only show the current authors associated HPOS woocommerce reviews for products that they created.

The only code that seems to handle the rest api is all-reviews.js inside \woocommerce\assets\client\blocks

document.addEventListener('DOMContentLoaded', function () {
    if (document.body.classList.contains('author')) {
        const authorId = window.wc_author_data.author_id;

        if (!authorId) {
            console.error('Author ID is not set.');
            return;
        }

        const originalFetch = wp.apiFetch;

        wp.apiFetch = function (options) {
            if (options.path && options.path.startsWith('/wc/store/v1/products/reviews')) {
                const url = new URL(options.path, window.location.origin);
                url.searchParams.set('author', authorId);
                options.path = url.pathname + url.search;
            }
            return originalFetch(options);
        };

        // Manually trigger a fetch request to test the override
        wp.apiFetch({ path: `/wc/store/v1/products/reviews?order=desc&orderby=date_gmt&per_page=10&offset=0&_locale=user&author=${authorId}` })
            .then(response => console.log('Fetch response:', response))
            .catch(error => console.error('Fetch error:', error));
    }
});

function filter_product_reviews_by_author($query) {
    if (defined('REST_REQUEST') && REST_REQUEST) {
        if (strpos($_SERVER['REQUEST_URI'], '/wc/store/v1/products/reviews') !== false) {
            $params = $_GET;
            if (isset($params['author']) && !empty($params['author'])) {
                $query->query_vars['user_id'] = intval($params['author']);
                error_log('Query modified to filter by author: ' . $params['author']);
            }
        }
    }
}
add_action('pre_get_comments', 'filter_product_reviews_by_author');

Based on this my current attempt shouldnt be necessary either: https://stackoverflow.com/a/70512403/1868159

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.