What steps are needed to successfully enable the callback function within the addFilter method from @wordpress/hooks while customizing the tables in WooCommerce analytics reports?

I've been diving into customizing Analytics reports tables for clients on our WooCommerce platform. I followed a guide at this link, but encountered an issue with the JavaScript file.

After adding the filter at the end of the file as instructed, nothing seems to happen when the addFilter function is called. The callback function never executes.

Below is the code snippet in question:

import { addFilter } from '@wordpress/hooks';

    console.log(addFilter)

function addCustomColumnsToWCReportTable( reportTableData ) {

    console.log("I'm in !!")
    
    const { endpoint, items } = reportTableData;
        if ( 'orders' !== endpoint ) {
            return reportTableData;
    
        }
    
    reportTableData.headers = [
        ...reportTableData.headers,
        {
            label: 'Order VAT Rate',
            key: 'vat_rate',
        },
    
    ];
    reportTableData.rows = reportTableData.rows.map( ( row, index ) => {
        const item = items.data[ index ];
        const newRow = [
            ...row,
            {
                display: item.vat_rate,
                value: item.vat_rate,
            },
        ];
        return newRow;
    } );
    
    return reportTableData;

}
addFilter( 'woocommerce_admin_report_table','custom_reports', addCustomColumnsToWCReportTable, 10 );

The fact that addFilter shows up in the console log indicates it should be functioning properly.

No errors are being thrown in the console, yet the expected console.log() message within the callback function is missing.

I attempted tweaking the hooks without success and explored various online resources for writing filters, though documentation is somewhat lacking.

The only output in the console related to addFilter existing is the following:

ƒ addHook(hookName, namespace, callback) {
    let priority = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 10;
    const hooksStore = hooks[storeKey];

    if (!(0,_validateHookN…

Answer №1

If you want to include your js file with the "wp-hooks" script as a dependency, follow these steps:

add_action( 'admin_enqueue_scripts', 'my_admin_scripts' );

function my_admin_scripts() {
   wp_enqueue_script( 'my-reports', 'path/to/script/my-reports.js', array('wp-hooks') );
}

Next, update your code by adding a const definition at the top - there is no need to include '@wordpress/hooks' anymore due to the dependency:

const { addFilter } = wp.hooks;
function addCustomColumnsToWCReportTable( reportTableData ) {

    console.log("i'm in !!")
    
    const { endpoint, items } = reportTableData;
        if ( 'orders' !== endpoint ) {
            return reportTableData;
    
        }
    
    reportTableData.headers = [
        ...reportTableData.headers,
        {
            label: 'Order VAT Rate',
            key: 'vat_rate',
        },
    
    ];
    reportTableData.rows = reportTableData.rows.map( ( row, index ) => {
        const item = items.data[ index ];
        const newRow = [
            ...row,
            {
                display: item.vat_rate,
                value: item.vat_rate,
            },
        ];
        return newRow;
    } );
    
    return reportTableData;

}
addFilter( 'woocommerce_admin_report_table','custom_reports', addCustomColumnsToWCReportTable, 10 );

This code has been tested and it works perfectly :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Distinction between Object.assign and the simple assignment operation

Could you please explain the distinction between these two lines of code? Object.assign(otherObject, { someNewProperty: '' }); vs. otherObject.someNewProperty = ''; Also, which one of these methods is more efficient in terms of sp ...

Issue: setAllcategories function not found

Currently engaged in using Next.js and Sanity as a Headless CMS for the backend. In the code snippet below, I have created a Categories.js file in the components folder to fetch some data. My objective is to extract all the titles from the category Array. ...

Why does Typescript not enforce a specific return type for my function?

In my custom Factory function, I need to return a specific type: type Factory<T> = () => T; interface Widget { creationTime: number; } const createWidget: Factory<Widget> = () => { return { creationTime: Date.now(), foo: &a ...

Exploring the integration of React with Spotify's Web Playback SDK

There is an exciting new beta feature on Spotify that allows for full song playback in the browser called the Web Playback SDK. The documentation showcases initializing a player immediately using script tags in the main HTML file, requiring an access token ...

Adding a value to an element in JavaScript to interact with it using Selenium

After implementing the provided code snippet, I noticed that it replaces the value in the element with a new one. However, I am looking to append or insert a new line rather than just replacing the existing value. Is there an alternative command like app ...

Tips for interpreting the JSON data returned by a Node server in Angular

When trying to implement a login form in my Angular frontend, I encountered an issue with reading the JSON object returned from my node.js server. Despite following the correct steps, the console displays "undefined" as if it cannot recognize the format. ...

Discovering the function responsible for styling a DOM elementDiscovering how to identify the

I have a Prestashop 1.6 store and I've noticed that when I scroll down, my main menu becomes fixed at the top of the page. However, when I scroll back up, it reverts to its default position in the header. The issue is that the height of the menu is se ...

Counting Clicks with the Button Counter

I'm having an issue with my jQuery code that is supposed to count button clicks - it stops after just one click. I need help fixing this problem. $(function() { $('.btn').click(function() { $(this).val(this.textContent + 1); }); } ...

Tips for selectively executing a script based on whether the DIV is within the viewport

I have a created a script as shown below: jQuery(function($) { $('.count').countTo({ from: 0, to: '400', speed: '3000', refreshInterval: 50, onComplete: func ...

How to display an image in a pop-up with a title

I am currently using the Bootstrap framework and I am trying to create a popup image with a title, but it only shows the image. I am not sure how to add code in JavaScript to display the title as well. Can someone please assist me? Here is my code: Javas ...

Guide to generating a div element with its contents using JSON

On my webpage, there is a button that increases the "counter" value every time it's clicked. I am looking to achieve the following tasks: 1) How can I generate a json file for each div on my page like the example below: <div class="text1" id="1" ...

Can someone explain the significance of '{}' within the function shown below?

I've been able to grasp most of this code, but I'm unsure about "{}". Can anyone clarify its meaning? var Toggle = function(section, expand) { this.section = section || {}; this.expand = expand | ...

Checking for the existence of a row in Node.js using Sqlite3

Wondering if it's possible to verify the existence of a row using node.js and the sqlite module. I currently have this function in place, but it always returns false due to the asynchronous nature of the module. function checkIfRowExists(username, pa ...

using jquery to retrieve the current time and compare it

This is the code I currently have: var currentTime = new Date() var month = currentTime.getMonth() + 1 var day = currentTime.getDate() var year = currentTime.getFullYear() var hours = currentTime.getHours() var minutes = currentTime.getMinutes() aler ...

Executing Basic Authentication in Javascript through window.open()

After a user logs into my app, they have the option to download a CSV file from the server by clicking on a button. The URL for the download is secured with basic authentication. When attempting to open the URL using the code below: window.open('http ...

Exploring the world of CouchDB through jQuery and AJAX POST requests while navigating

I am in the process of building a simple web application. Today, I installed Couch 1.3.1 and set up a database. I am currently trying to save a document to my local Couch (localhost:5984) using a POST request from a client browser that is also on localhost ...

JavaScript code to copy a specified column through the last column, and then paste it down to the last row

I have limited experience with JavaScript and I've been putting together the code I need by searching online resources and watching videos. My goal is to set multiple columns in row 4, starting from column 18 to the last column, as the active cells fo ...

What is the reason for webpack searching for jQuery even though it is not necessary for the module?

Before I proceed with my question, I want to clarify that I may not fully grasp the intricacies of this issue and I apologize if it does not meet the standards of Stackoverflow's Q&A. Currently, we are facing a challenge in our project while tryi ...

Requesting data from a server using jQuery's AJAX functionality

Currently, I am utilizing the following piece of code for an ajax call: $('#filter').submit(function(){ var filter = $('#filter'); $.ajax({ url:filter.attr('action'), data:filter.serialize(), // form ...

Designate a Cookie for individual users

Currently, I am in the process of building a straightforward Wordpress website that aims to monitor a user's order using a specific Cookie. Although most of the functionalities are already implemented, an unexpected issue has surfaced. Upon logging i ...