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

Simple methods for ensuring a minimum time interval between observable emittance

My RxJS observable is set to emit values at random intervals ranging from 0 to 1000ms. Is there a way to confirm that there is always a minimum gap of 200ms between each emission without skipping or dropping any values, while ensuring they are emitted in ...

Create a unique V-MODEL for each index that I generate

How can I customize the V-MODEL for each object generated? I am developing a cupcake website where users can create multiple forms with just one submission. However, when generating two fields, the inputs of the second field are linked to the inputs of t ...

Consistently encountering incorrect values during onClick events

I am using a Table to display certain values const [selected, setSelected] = React.useState<readonly number[]>([]); const isSelected = (id: number) => selected.indexOf(id) !== -1; return ( <TableContainer> <Table sx={{ width ...

Creating a function to update data in a Node.js/MongoDB environment

Hey there! I'm new to working with nodejs and mongodb, and I'm trying to create a function that updates the win, lose, and draw record in my UserSchema. Here's my Schema: UserSchema = new mongoose.Schema({ username:'string', ...

Issue with Electron Remote process failing to take user-defined width and height inputs

I'm currently facing an issue with utilizing remote windows in electron. I am attempting to process user input and use that input to generate a new window with specific width and height. However, when I hit submit, nothing happens. I can't figur ...

Can someone clarify the distinction between returning a value directly or using Promise.resolve within the then() function?

What is the distinction between: new Promise(function(res, rej) { res("first example"); }) .then(function(result) { return "bbb"; // directly returning string }) .then(function(result) { console.log(result); }); and this: n ...

Is utilizing v-model to update the Vuex store a recommended practice?

Hello there! As a newcomer to Vue, I find myself facing a dilemma that has been weighing on my mind. I'm confused about whether we should utilize the v-model directive to make changes to the Vuex store. While Vuex guidelines suggest modifying the stor ...

Transform a delimited string and an array of objects into a new format

Is there a way to easily convert a delimited string into an array of objects with data binding functionality? ng-list is suitable for arrays of strings. However, I have an array of objects where I want to delimit the text property for easy editing. Works ...

Updating Ajax data leads to improved sorting capabilities

When making an AJAX call on my Wordpress site, everything works perfectly except for the sorting of the data in the SUCCESS function. If I use print_r ($service), I can see that the correct custom order is being validated However, after sending it using: ...

Implement dynamic configuration injection by allowing users to specify the name of a configuration file during runtime, instead of having it fixed in the code

In my development using webpack, I am exploring ways to make my application configurations more dynamic. Presently, the project is a create-react-app that has been ejected. For instance, when creating a local build in my package.json file, I include the f ...

Displaying a progress bar during image uploads in PHP without using AJAX

I am in the process of uploading a file on my website and it is working well. However, I would like to display a progress bar while the upload is taking place. I have considered using ajax for this purpose, but I am unable to use ajax. Is there a way to ac ...

Exploring the correlation between aggregation operations in MongoDB and MapReduce techniques

For days, I've been grappling with translating this specific query into MapReduce. My task is to determine the number of different cars that have covered a distance of "N" kilometers. The Query: db.adsb.group({ "key": { "KM": true }, ...

Utilizing Ionic Storage to set default request headers through an HTTP interceptor in an Angular 5 and Ionic 3 application

I'm attempting to assign a token value to all request headers using the new angular 5 HTTP client. Take a look at my code snippet: import {Injectable} from '@angular/core'; import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from ...

How can Vue detect modifications made in the edited field?

I am facing an issue with tracking changes in a specific object. Here is the structure of the object: users: { email: '', password: '' } My goal is to detect any edits made to the keys within the users object and store the key ...

Enhancing parent component props in React-router-dom: A guide to updating them

Here is the structure of my App component: const App = (props) => ( <BrowserRouter> <PageTheme {...some props I'd like to change on route change}> <Switch> <Route exact path="/example"> <E ...

Executing a NestJs cron job at precise intervals three times each day: a guide

I am developing a notifications trigger method that needs to run three times per day at specific times. Although I have reviewed the documentation, I am struggling to understand the regex code and how to customize it according to my requirements! Current ...

How to use plain JavaScript to extract the value from a textarea in GWT

Situation: I am currently developing a tampermonkey script to enhance certain GWT pages within a third-party application. Unfortunately, I do not have access to the source code or servers. Challenge: My task is to retrieve the value of a textarea element ...

Understanding TypeScript typing when passing arguments to the Object.defineProperty function

After reviewing all the suggested answers, including: in Typescript, can Object.prototype function return Sub type instance? I still couldn't find a solution, so I'm reaching out with a new question. My goal is to replicate Infix notation in J ...

Why does Googlebot need to retrieve HTML from JSON-exclusive URLs?

Link to a page like this: The following code is found: $.getJSON("/newsfeeds/61?order=activity&amp;type=discussion", function(response) { $(".discussion-post-stream").replaceWith($(response.newsfeed_html)); $(".stream-posts").before($("<div cl ...

Using ajax for sending data is a breeze, but I am encountering trouble when attempting to receive data back from

I have a function that retrieves a value from an input and sends data through ajax to another PHP file. However, I am facing an issue where I cannot retrieve the result back from the PHP file even though I echo it in the ajax success function. <script&g ...