Use a direct query to retrieve Ninja Forms submissions for a specified date range.
In June I wrote code to display Ninja Forms submissions. I had planned to use that code on the Community Awareness of Drugs site to send a nightly email with a list of submissions received the previous day.
Down the rabbit hole
In that previous post I used Ninja_Forms()->form( $id )->get_subs() to retrieve all the submissions for a specific form. I then used the submission date (get_sub_date()) to find ones in a particular date range.
When trawling through the Ninja Forms source (version 3.4.20 hasa massive 930 files; Contact Form 7 has 79 files!) I saw that the get_subs() function could accept a $where parameter. I spent hours searching, reading, experimenting and stepping through the code trying to pass a date range to the function but no luck. It was quite the waste of time – it was foolish of me not to give up and move to what became the eventual solution.
When there is an API available I always try to use it, unless there is a compelling reason to do a direct query with WP_Query or get_posts() e.g. the API is very very slow or I just can’t get things to work via the API.
Ninja Forms uses get_posts() to retrieve the submissions. There is even a comment in one file that made me feel better:
You can also use WordPress queries, since this is a custom post type.
I created a query with a date query. I chose to only request the post IDs of the submissions because the post meta, which has all the submitted data, needs processing before it’s useful. I’ve left this processing to the Ninja Forms API (via the $submission->get_field_value() function).
I added one TODO to the script – to suggest moving the retrieving of each field’s id, key and value to outside the submissions loop. I had wasted so much time on the $where testing that I didn’t have the energy to refactor the script to do this.
The code is a standalone script and Query Monitor results are not displayed so I don’t know how many queries are being performed or whether the code is efficient. I could move it into a page template do examine its performance.
Here’s a screenshot of the resulting output.
It would not take many changes to use this as a scheduled cron task.
For the Community Awareness of Drugs site I would have to create a number of intermediate arrays because each form on that site has a select field with course dates. The submissions would have to be split based on that field’s value. It’s not too difficult once you get a good picture of the array in your head. Some day I will get to that.