This will only work if
example:
/********************************************************** add ?delivery or ?pickup parameter to a link something like **********************************************************/ <a href="http[s]://[my-domain.com]/?pickup">Some link text </a> /* set to pickup */ <a href="http[s]://[my-domain.com]/?delivery">Some link text</a> /* set to delivery*/ <a href="http[s]://[my-domain.com]/?foo=1&bar=2&pickup">Some link text</a> /* set to pickup */ <a href="http[s]://[my-domain.com]/?foo=1&bar=2&delivery">Some link text</a> /* set to delivery*/ <a href="http[s]://[my-domain.com]/?foo=1&bar=2&pickup">Some link text</a> /* set to pickup */ <a href="http[s]://[my-domain.com]/?foo=1&bar=2&delivery">Some link text</a> /* set to delivery*/ <a href="http[s]://[my-domain.com]/?foo=1&bar=2&pickup=1">Some link text</a> /* set to pickup */ <a href="http[s]://[my-domain.com]/?foo=1&bar=2&delivery=1">Some link text</a> /* set to delivery*/ ...etc...
If the “pickup” and or “delivery” parameter is already being used elsewhere, you can change this by using a constant like so in your wp-config.php:
define('WPPIZZA_GET_DELIVERY', 'x4delivery'); define('WPPIZZA_GET_PICKUP', 'x4pickup');
in which case the links above would then need to be
&x4delivery &x4pickup
respectively
]]>example function myprefix_update_wppizza_prices:
/* IMPORTANT: RUN THIS ONE TIME ONLY AND DELETE/DISABLE THIS SCRIPT AGAIN WHEN YOU ARE DONE OR YOU WILL CONTINUALLY BE ADDING 10% ON TOP OF 10% YOU COULD ALSO ADD AN ADDITIONAL META DATA FLAG PERHAPS TO MAKE SURE IT ONLY GETS UPDATED IF THIS FLAG IS NOT SET YET, BUT I LEAVE THIS UP TO THE YOU AS TO HOW OR IF YOU WANT TO DO THAT . IN ANY EVENT: I STRONGLY SUGGEST YOU MAKE A BACKUP FIRST AND - AS ALWAYS - USE AT YOUR OWN RISK */ /* script must be run on init or later or things will not work */ add_action( 'init', 'myprefix_update_wppizza_prices'); function myprefix_update_wppizza_prices(){ /* the percentage to add to all prices change as required */ $percent = 10; /* conditionals: only runs if - logged into WP admin - logged in user has 'wppizza_cap_menu_items' capabilities - the _GET['runonce'] parameter is set (so as to only run it one time , see above) */ if( is_admin() && current_user_can('wppizza_cap_menu_items') && isset($_GET['runonce'])){ //print info print"------------ START UPDATING WPPIZZA ITEMS PRICES --------------
".PHP_EOL; //wppizza post type $postType = 'wppizza'; //get all wppizza menu items $menuItems = get_posts(array('post_type' => $postType,'numberposts' => -1)); //loop through menu items, getting current prices , add 10% to each price and resave meta foreach($menuItems as $menuItem){ //print info print PHP_EOL."
UPDATING ".$menuItem -> post_title." [ID ".$menuItem -> ID."]
".PHP_EOL; //get current menu item meta data $objMetaData = get_post_meta($menuItem -> ID, $postType, true ); //loop through prices foreach($objMetaData['prices'] as $key => $price){ //adding 10 percent.... $objMetaData['prices'][$key] *= (1 + $percent / 100); //round as per plugin settings.... $objMetaData['prices'][$key] = wppizza_round($objMetaData['prices'][$key]); //print info print" - old price: " . $price . " | new price : " . $objMetaData['prices'][$key] . "
".PHP_EOL; } //re-save meta - comment this line out if you want to view the results first update_post_meta($menuItem -> ID, $postType, $objMetaData) ; } //print info print"----- ALL PRICES UPDATED, DELETE/DISABLE THIS SCRIPT NOW !!! -------"; exit(); } return; }
Usage:
To run this script, add it somewhere where it would be read (your functions.php for example) login to the WP backend and go to http[s]://[your-domain]/wp-admin/?runonce=1 .
DO NOT RELOAD THAT PAGE – SEE ABOVE. The one screen message will tell you when it’s done.
If you want to do the same with the prices of any ingredients of the “WPPizza Add Ingredients” plugin you could do the following in a similar fashion
//script must be run on init or later or things will not work add_action( 'init', 'myprefix_update_wppizza_ingredients_prices'); function myprefix_update_wppizza_ingredients_prices(){ /* the percentage to add to all ingredients prices change as required */ $percent = 10; //same conditional as above if( is_admin() && current_user_can('wppizza_cap_menu_items') && isset($_GET['runonce'])){ //ingredients options slug $options_slug = 'wppizza_addingredients'; //get current ingredients option $ai_options = get_option($options_slug, 0); //loop through ingredients , add 10% to each price if(!empty($ai_options['ingredients'])){ foreach($ai_options['ingredients'] as $key => $ingredient){ if(!empty($ingredient['prices'])){ foreach($ingredient['prices'] as $pKey => $price){ $ai_options['ingredients'][$key]['prices'][$pKey] *= (1 + $percent / 100); $ai_options['ingredients'][$key]['prices'][$pKey] = wppizza_round($ai_options['ingredients'][$key]['prices'][$pKey]); }} }} /* re-save options back to db */ update_option($options_slug, $ai_options ); //print info print"----- ALL INGREDIENTS PRICES UPDATED, DELETE/DISABLE THIS SCRIPT NOW !!! --------"; exit(); } return; }]]>
A few examples as to how you can show/hide/add/modify input formfields available on the checkout page
If you wish to simply show hide some formfields when an order is set to be a pickup order.
See here , for options as to where to add this css
example:
/********************************************************** target specific elements on pickup use your browsers element inspector to ascertain the exact classname you need to target **********************************************************/ .wppizza-order-ispickup .wppizza-personal-details > .wppizza-cname{display:none} .wppizza-order-ispickup .wppizza-personal-details > .wppizza-caddress{display:none} /* etc etc */
Make sure to not hide things that you have also set to be “required” (unless they are already prefilled in some way) or the customer will never be able to check out …
Add / modify a formfield on the checkout page. First of all, you can of course already add/remove and conditionally set various formfield properties by going to WPPizza ->Order Form
. If you however need some more granular control or simply add your own, see the examples below
.
example:
/*************************************************** add the filter and corresponding function ****************************************************/ add_filter('wppizza_register_formfields', 'my_prefix_modify_wppizza_formfields'); function my_prefix_modify_wppizza_formfields($formfields){ /* *unique* identifier for the formfield you want to add if you add more than one, each one must be a unique id for simplicity and demonstration purposes the some is being used here for all ! if you wish ta alter an already existing formfield use that formfields key instead a print_r($formfields) will show you all registered formfields and their keys if you need to identify a particular one */ $unique_ident = 'my_unique_formfield_id'; /*********************************************** adding a text formfield ***********************************************/ $formfields[$unique_ident ] = array( /* sort order - at which position is this field displayed */ 'sort' => 100, /* the unique ident */ 'key' => $unique_ident , /* label displayed for the formfield */ 'lbl' => 'some label', /* should be defined as an array, with the first value being false */ 'value' => array(false), /* set to text to display a text input */ 'type' => 'text', /* true to enable (pointless to set this to false)*/ 'enabled' => true, /* true to make the field required on delivery, false otherwise */ 'required' => true, /* true to make the field required on pickup, false otherwise */ 'required_on_pickup' => true, /* true to prefill with a value if it is known (will only ever do anything with 'onregister' being true as well) */ 'prefill' => false, /* true to make field part of the user registration values */ 'onregister' => false, /* true to add the value entered to the email subject */ 'add_to_subject_line' => false, /* input placeholder */ 'placeholder' => 'my placeholder', /* validation as available wppizza->order form. as there can be multiple validation rules, this should be an array*/ 'validation' => array( 'default' => true, ), ); /*********************************************** adding a select dropdown ***********************************************/ $formfields[$unique_ident ] = array( /* sort order - at which position is this field displayed */ 'sort' => 100, /* the unique ident */ 'key' => $unique_ident , /* label displayed for the formfield */ 'lbl' => 'some label', /* an array of available dropdown values*/ 'value' => array('1st value','2nd value','3rd value','Nth value'), /* set to select to display a select dropdown*/ 'type' => 'select ', /* true to enable (pointless to set this to false)*/ 'enabled' => true, /* true to make the field required on delivery, false otherwise */ 'required' => true, /* true to make the field required on pickup, false otherwise */ 'required_on_pickup' => true, /* true to prefill with a value if it is known (will only ever do anything with 'onregister' being true as well) */ 'prefill' => false, /* true to make field part of the user registration values */ 'onregister' => false, /* true to add the value entered to the email subject */ 'add_to_subject_line' => false, /* placeholder - used as initial, non-selected value or bool false / empty */ 'placeholder' => '--please select--', /* validation as available wppizza->order form. as there can be multiple validation rules, this should be an array, however as this is a select field , the rules as set below are really the only sensible setting here */ 'validation' => array( 'default' => true, ), ); /*********************************************** adding radio inputs ***********************************************/ $formfields[$unique_ident ] = array( /* sort order - at which position is this field displayed */ 'sort' => 100, /* the unique ident */ 'key' => $unique_ident , /* label displayed for the formfield */ 'lbl' => 'some label', /* an array of available radio values*/ 'value' => array('1st value','2nd value','3rd value','Nth value'), /* set to select to display radio choices */ 'type' => 'radio', /* true to enable (pointless to set this to false)*/ 'enabled' => true, /* true to make the field required on delivery, false otherwise */ 'required' => true, /* true to make the field required on pickup, false otherwise */ 'required_on_pickup' => true, /* true to prefill with a value if it is known (will only ever do anything with 'onregister' being true as well) */ 'prefill' => false, /* true to make field part of the user registration values */ 'onregister' => false, /* true to add the value entered to the email subject */ 'add_to_subject_line' => false, /* ignored for radios */ 'placeholder' => false, /* validation as available wppizza->order form. as there can be multiple validation rules, this should be an array, however as these are radio inputs, the rules as set below are really the only sensible setting here */ 'validation' => array( 'default' => true, ), ); /*********************************************** adding a checkbox ***********************************************/ $formfields[$unique_ident ] = array( /* sort order - at which position is this field displayed */ 'sort' => 100, /* the unique ident */ 'key' => $unique_ident , /* label displayed for the checkbox */ 'lbl' => 'some label', /* ignored, but should be set to avoid php notices*/ 'value' => array(false), /* set to select to display multiple checkbox choices */ 'type' => 'checkbox', /* true to enable (pointless to set this to false)*/ 'enabled' => true, /* true to make the field required on delivery, false otherwise */ 'required' => true, /* true to make the field required on pickup, false otherwise */ 'required_on_pickup' => true, /* true to prefill with a value if it is known (will only ever do anything with 'onregister' being true as well) */ 'prefill' => false, /* true to make field part of the user registration values */ 'onregister' => false, /* true to add the value entered to the email subject */ 'add_to_subject_line' => false, /* ignored for checkboxes*/ 'placeholder' => false, /* validation as available wppizza->order form. as there can be multiple validation rules, this should be an array, however as these are radio inputs, the rules as set below are really the only sensible setting here */ 'validation' => array( 'default' => true, ), ); /*********************************************** adding multiple checkbox choices ***********************************************/ $formfields[$unique_ident ] = array( /* sort order - at which position is this field displayed */ 'sort' => 100, /* the unique ident */ 'key' => $unique_ident , /* label */ 'lbl' => 'some label', /* an array of checkboxes */ 'value' => array('1st value','2nd value','3rd value','Nth value'), /* set to select to display multiple checkbox choices */ 'type' => 'multicheckbox', /* true to enable (pointless to set this to false)*/ 'enabled' => true, /* true to make the field required on delivery, false otherwise */ 'required' => true, /* true to make the field required on pickup, false otherwise */ 'required_on_pickup' => true, /* true to prefill with a value if it is known (will only ever do anything with 'onregister' being true as well) */ 'prefill' => false, /* true to make field part of the user registration values */ 'onregister' => false, /* true to add the value entered to the email subject */ 'add_to_subject_line' => false, /* ignored for checkboxes*/ 'placeholder' => false, /* validation as available wppizza->order form. as there can be multiple validation rules, this should be an array, however as these are radio inputs, the rules as set below are really the only sensible setting here */ 'validation' => array( 'default' => true, ), ); /*********************************************** adding a hidden formfield ***********************************************/ $formfields[$unique_ident ] = array( /* sort order - at which position is this field displayed */ 'sort' => 100, /* the unique ident */ 'key' => $unique_ident , /* ignored for hidden fields */ 'lbl' => false, /* should be defined as an array, with the first value being false */ 'value' => array(false), /* set to hidden to display a hidden input */ 'type' => 'hidden', /* true to enable (pointless to set this to false)*/ 'enabled' => true, /* true to make the field required on delivery, false otherwise . Warning: if you set this to true, without prefilling it (see below) the customer will never be able to order when delivery is selected ! */ 'required' => true, /* true to make the field required on pickup, false otherwise . Warning: if you set this to true, without prefilling it (see below) the customer will never be able to order when pickup is selected ! */ 'required_on_pickup' => true, /* true to prefill with a value if it is known (will only ever do anything with 'onregister' being true as well) */ 'prefill' => false, /* true to make field part of the user registration values */ 'onregister' => false, /* true to add the value entered to the email subject */ 'add_to_subject_line' => false, /* ignored for hidden fields */ 'placeholder' => false , /* validation as available wppizza->order form. as there can be multiple validation rules, this should be an array, however as this is a hidden inputs, the rules as set below are really the only sensible setting here */ 'validation' => array( 'default' => true, ), ); /*********************************************** removing a formfield simply unset , or disable ***********************************************/ unset($formfields[$unique_ident]); //unset $formfields[$unique_ident]['enabled'] = false ; //disable /*********************************************** if you want to disable/not show a field when pickup is selected ***********************************************/ if(wppizza_is_pickup()){//simply use !wppizza_is_pickup() for the reverse unset($formfields[$unique_ident]); //unset $formfields[$unique_ident]['enabled'] = false ; //disable } return $formfields; }
For additional conditionals that might be useful (‘cart is empty’ and similar), also see here
If a formfield is set to have ‘onregister’ and ‘prefill’ set to true, the relevant value will be prefilled/selected when a user logs in, if you want to or need to (especially with hidden fields) always pre-set a specific value I’d suggest something like the below
example:
add_action('init', 'myprefix_prefill_formfields'); function myprefix_prefill_formfields(){ /* prefill a value if it has not ever been set *unique* identifier for the formfield you want to prefill */ $unique_ident = 'my_unique_formfield_id'; if(!isset($_SESSION[WPPIZZA_SLUG.'_userdata'][$unique_ident])){ /* text / hidden formfields */ $_SESSION[WPPIZZA_SLUG.'_userdata'][$unique_ident] = 'some input value'; /* radios - one of the values as defined in 'value' array of the registered formfield*/ $_SESSION[WPPIZZA_SLUG.'_userdata'][$unique_ident] = '2nd value'; /* checkbox (single) - boolean */ $_SESSION[WPPIZZA_SLUG.'_userdata'][$unique_ident] = true; //bool /* checkbox (multiple) - one or more of the values as defined in 'value' array ofthe registered formfield*/ $_SESSION[WPPIZZA_SLUG.'_userdata'][$unique_ident] = array('1st value','3rd value') ; //array } return; }]]>
/*** email subject lines are made up of 3 parts filter each part as required based on your preferences ****/ add_filter('wppizza_filter_email_subject', 'myprefix_filter_email_subject', 10, 2); function myprefix_filter_email_subject($subject, $order_formatted){ /* defaults //dynamic depending on settings in wppizza order form , but typically its the site name plus perhaps some personal info */ $subject['prefix'] = '[--------- conditional/dynamic text ---------------]' ; //from wppizza->localization $subject['main'] = $order_formatted['localization']['your_order']; //date/time according to wordpress date/time settings */ $subject['suffix'] = date_i18n($order_formatted['date_format']['date'], WPPIZZA_WP_TIME)." ".date_i18n($order_formatted['date_format']['time'], WPPIZZA_WP_TIME).""; //This typically produces something like "My Shop Your Order March 25, 2020 6:31 pm" where: $subject['prefix'] = 'My Shop'; $subject['main']= 'Your Order'; $subject['suffix']= 'March 25, 2020 6:31 pm'; */ // example: if you want to not add the date/time at the end $subject['suffix'] = ''; //or simply unset($subject['suffix']); // example: change the typically main "My Order" $subject['main'] = 'whatever it is you want'; // example: add something after it all $subject['some_additional_key'] = 'something added to the end of the subject line; /* for conditionals depending on order values, you can use the 2nd "$order_formatted" parameter */ return $subject; }
As of version 3.6.7+ an additional parameter has been added to the filter with the order details already formatted
add_filter('wppizza_filter_email_subject', 'prefix_filter_email_subject', 10 , 3); function prefix_filter_email_subject($subject, $order, $order_formatted){ /* $subject is an array made up of $subject['prefix'] - typically contains blogname followed by items added to subject line in wppizza->order form $subject['main'] - typically contains "your order" localization string (wppizza->localization) $subject['suffix'] - typically contains date of order according to date/time format set in WP->settings */ /* example: adding the label of a gateway as set in wppizza->gateways after the prefix , tweak as required*/ $subject['prefix'] .= ' '.$order_formatted['ordervars']['payment_type']['value_formatted']; /* example2: adding the paymet method (i.e typically simply "Cash" or "Credit Card" ) , tweak as required*/ $subject['prefix'] .= ' '.$order_formatted['ordervars']['payment_method']['value_formatted']; /* see $order_formatted for all available parameters */ return $subject; }
If you require more granular control over email parameters, you can also use the ‘wppizza_filter_email_settings’ filter (I believe the attributes are self-explanatory)
add_filter('wppizza_filter_email_settings', 'prefix_filter_email_settings', 10 , 3); function prefix_filter_email_settings($email_settings, $recipient_key, $order_formatted){ /* do your thing */ return $email_settings; }]]>
Note: Documentation for extensions and gateways will always be work in progress and will expand over time.
]]>example to have different openingtimes if a user chooses pickup (pickup must of course be enabled to start off with)
Note: The example using the ‘wppizza_shop_is_open’ filter mentioned here previously may run to late in some circumstances. Updating your implementation as outlined below is advised.
@param: array
@return: array
example
/*** get/set the opening hours depending on whether it's pickup or delivery which opens/closes the shop as appropriate ****/ add_filter('wppizza_filter_options_openingtimes', 'myprefix_filter_pickup_opening_times'); function myprefix_filter_pickup_opening_times($openingtimes){ /* check current selection is pickup or delivery and if pickup, override the opening times */ $is_pickup = wppizza_is_pickup();//returns bool true|false if($is_pickup){ /* mondays */ $openingtimes['opening_times_standard'][1]['open'] = '10:00'; $openingtimes['opening_times_standard'][1]['close'] = '12:00'; /* tuesdays */ $openingtimes['opening_times_standard'][2]['open'] = '10:00'; $openingtimes['opening_times_standard'][2]['close'] = '12:00'; /* wednesdays */ $openingtimes['opening_times_standard'][3]['open'] = '10:00'; $openingtimes['opening_times_standard'][3]['close'] = '12:00'; /* thursdays */ $openingtimes['opening_times_standard'][4]['open'] = '10:00'; $openingtimes['opening_times_standard'][4]['close'] = '12:00'; /* fridays */ $openingtimes['opening_times_standard'][5]['open'] = '10:00'; $openingtimes['opening_times_standard'][5]['close'] = '12:00'; /* saturdays */ $openingtimes['opening_times_standard'][6]['open'] = '10:00'; $openingtimes['opening_times_standard'][6]['close'] = '12:00'; /* sundays */ $openingtimes['opening_times_standard'][0]['open'] = '10:00'; $openingtimes['opening_times_standard'][0]['close'] = '12:00'; /* unset - if required - your custom opening times */ $openingtimes['opening_times_custom'] = array(); /* unset - if required - any closing times */ $openingtimes['times_closed_standard'] = array(); } /* return opening times as filtered (or not as the case may be) */ return $openingtimes; }
ensure the toggle is always visible as – by default – it would not be displayed if the shop is shut so there would be no way to choose a different delivery method
@param: void
@return: bool
example:
/* always show pickup/delivery option */ add_filter('wppizza_filter_force_pickup_toggle_display', 'myprefix_pickup_openingtimes_force_toggle'); function myprefix_pickup_openingtimes_force_toggle(){ return true; }
If you are using the “WPPizza Preorder” plugin while also applying different opening times for pickup as outlined above, you must also ensure you have *NOT* enabled the “Caching” option in the options settings page of the “Preorder” plugin.
]]>if you want to develop you own script/plugin etc based on any wppizza orders, please refer to the documentation below
Note: Result sets will always be sorted by order date in descending order
@ since 3.5
@ param array
@ return array
Note: compared to the now removed get_orders_completed() all dimensions of the returned array are arrays themselves now. no more mix ‘n’ match between arrays and objects
The following values will be used when not setting ANY arguments (which is essentially the default before any dropdown options might be selected in WPPizza -> Order History)
$args = array( 'query' => array( 'wp_user_id' => false , 'email' => false , 'order_id' => false , 'hash' => false , 'payment_status' => array('COMPLETED', 'UNCONFIRMED', 'REFUNDED', 'REJECTED') , 'order_status' => false , 'custom_status' => false , 'blogs' => {default depends on options set and if it's a multisite setup. see notes below}, 'summary' => false , ), 'pagination' => array( 'paged' => 0 , 'limit' => {default depends on options set. see notes below}, ), 'format' => true , ) //run query, and get results $orders = wppizza_get_orders($args); //this would be the same as simply using $orders = wppizza_get_orders();
query the wppizza orders table according set parameters
int
false
str|array
false
int
false
str
false
str|array
array('COD', 'COMPLETED', 'UNCONFIRMED', 'REFUNDED', 'REJECTED')
'COD', 'COMPLETED', 'UNCONFIRMED', 'CAPTURED', 'REFUNDED', 'REJECTED', 'INPROGRESS', 'INITIALIZED', 'AUTHORIZED', 'CANCELLED', 'PAYMENT_PENDING', 'FAILED'
mixed (false|str|array)
false
'NEW','ACKNOWLEDGED','ON_HOLD','PROCESSED','DELIVERED','REJECTED','REFUNDED','OTHER','CUSTOM_1','CUSTOM_2','CUSTOM_3','CUSTOM_4'
mixed (false|str|array)
not set
timestamp (integer)
not set
timestamp (integer)
none
mixed (bool|array)
bool (see notes below)
bool
false
query an order for a specific meta key/value
see bottom of this page how to add meta values to an order
array of column/value arrays
void
limit results set of the query – ignored if ‘summary’ => true or only querying for a specific ‘order_id’ or ‘hash’ for a single blog only (as it will only ever return one result at most)
int
0
int
[int]
– as per option set in “WPPizza->Settings->Order History : Max Results”format the output for each order defaults to true. Set to false for unformatted order results – ignored if $args[‘query’][‘summary’] is set
bool
false
bool
false
Get completed orders for a user with user id 23 (use 0 to query orders from guest/non-registered customers) from the current blog only, limited to first 5 results with output being formatted
Query:
$args = array( 'query'=>array( 'wp_user_id' => 23 ,//user id 'payment_status' => 'COMPLETED',//completed only 'blogs' => false ,//current blog only ), //order values returned for the first 5 orders found (always by descending date) 'pagination' =>array( 'paged' => 0 , 'limit' => 5 , ), //formatting omitted, defaults to true ); $orders = wppizza_get_orders($args);
Results [Array]:
[total_number_of_orders] => 194 // [int] total number of orders found without pagination limit [total_value_of_orders] => 14265.59 //[float] total value of orders found without pagination limit [gateways_idents] => Array // [array] of all gateways used in results set ( [COD] => COD ) [number_orders_on_page] => 5 //[int] total number of orders within pagination limit [value_orders_on_page] => 269.17 //[float] total value of orders within pagination limits /* array of order values for each order returned withing pagination limits the key for each order is always made up of [blog_id]_[order_id] but you can also get the blog id in [site][blog_id][value] and the order id in [ordervars][order_id][value] */ [orders] => Array ( [1_623] => Array ( [site] => Array ( /*.... site data for this order ....*/ ) [ordervars] => Array ( /*.... general ordervars data for this order....*/ ) [customer] => Array ( /*.... customer data for this order....*/ ) [order] => Array ( /*.... cart items ....*/ ) [summary] => Array ( /*.... summary of order ()....*/ ) ) [1_622] => Array ( /* second order results set */ ) /* more order results */ )
Get completed or confirmed orders with an order status of ‘NEW’ and ‘meta_key’ equals ‘mymetakey’ and ‘meta_value’ equals ‘mymetavalue’. ()
Query:
$args = array( 'query'=>array( 'payment_status' => array('CONFIRMED', 'COMPLETED'),//completed only 'order_status' => 'NEW',//get orders with status NEW only ), 'meta'=>array( 'query' => array( //if you do not want to restrict by meta_key, omit array( 'column' => 'meta_key', 'value' => 'mymetakey', ), //if you do not want to restrict by meta_value, omit array( 'column' => 'meta_value', 'value' => 'mymetavalue', ), ), ), ); $orders = wppizza_get_orders($args);
Results set returned will be as above, restricted to all orders that match the meta query as well
Get completed orders of all users (including non-registered/guests) from all blogs, limited to first x results as set in “WPPizza->Settings->Order History : Max Results” with output being formatted and added class idents
Query:
global $wppizza_options; $args = array( 'query'=>array( 'payment_status' => 'COMPLETED', 'blogs' => true,//will be ignored if not in a multisite setup or simply omit entirely ), 'pagination' =>array( 'paged' => 0 , 'limit' => $wppizza_options['settings']['admin_order_history_max_results'] , ), 'format' => array( 'class_idents' => true, ), ); $orders = wppizza_get_orders($args);
Results [Array]:
/* as above example, but with class-indent added to each order parameter you could use in any outputs for consistent class names (perhaps adding a distinct prefix to each class name as well) so the order date would now return somthing like this */ [orders] => Array ( [1_623] => Array ( ............ [ordervars] => Array ( [order_date] => Array ( [label] => Order Date : [value] => 2018-05-15 00:48:08 [value_formatted] => May 15, 2018 12:48 am [class_ident] => order-date //this parameter is now added to each one ) ............ ) ............ ) [1_623] => Array ( /* second order */ ) ///etc )
Simply check if there are any new orders, without returning each orders values
Query:
$args = array( 'query'=>array( 'payment_status' => 'COMPLETED',//get completed orders only 'order_status' => 'NEW',//get orders with status NEW only 'summary' => true,// only return count/totals ), ); $orders = wppizza_get_orders($args);
Results [Array]:
[total_number_of_orders] => 194 // [int] total number of orders found without pagination limit [total_value_of_orders] => 14265.59 //[float] total value of orders found without pagination limit /* no other parameters will get returned */
If you are outputting the order results somehow/somewhere you could use the below helper to add pagination
@ param [int] : should be the total number of orders returned by order query before limit @ param [int] : should equal the limit set in the orders query pagination['limit'] parameter @ param [int] (default:false if omitted) : if set to an integer (2 for example) will display a max of 2 pagination links either side of current page, and use '...' where appropriate. false to show all links @ param bool (default:true if omitted) : true to display some pagination info underneath button , false to omit @ param false|int (default:false if omitted): links to current page. set a distinct post id to link to the page with this id (might be required for ajax requests) @ return str $pagination = wppizza_orders_pagination($total_no_of_orders, $limit, $ellipsis, $pagination_info, $post_id); print $pagination;
Adding Meta Data to an Order
/* adding 'mymetakey' with a value of 'mymetavalue' to an order, *when an order gets submitted* if mymetavalue is not a string/integer it will be serialized */ add_action('wppizza_add_order_meta', 'myprefix_add_order_meta', 10, 2) /*------------------------------------------------------------------------------ # $param order id # $param order values # $returns int (meta_id added) ------------------------------------------------------------------------------*/ function myprefix_add_order_meta($order_id, $order){ $meta_id = wppizza_do_order_meta($order_id, 'mymetakey', 'mymetavalue'); return $meta_id; }
/* adding 'mymetakey' with a value of 'mymetavalue' to an order, *even BEFORE an order gets submitted - i.e as soon as the user arrives on your orderpage * if mymetavalue is not a string/integer it will be serialized Note: if you also use 'wppizza_add_order_meta' with the same metakey, 'wppizza_add_order_meta' will overwrite the value captured with 'wppizza_add_order_meta_init' (as it happens after) */ add_action('wppizza_add_order_meta_init', 'myprefix_add_order_meta_init', 10, 1) /*------------------------------------------------------------------------------ # $param order id # $returns int (meta_id added) ------------------------------------------------------------------------------*/ function myprefix_add_order_meta_init($order_id){ $meta_id = wppizza_do_order_meta($order_id, 'mymetakey', 'mymetavalue'); return $meta_id; }
Updating Meta Data for an Order
/* updating metavalues for a specific meta_key relating to a specific order if it the meta_key for this order does not exist yet, it will be added, else the value will be updated if $meta_value is not a string/integer it will be serialized */ /*------------------------------------------------------------------------------ # $param int - order id we are updating # $param str - meta key we are updating # $param mixed - value to update/insert # $returns int (meta_id added/updated) ------------------------------------------------------------------------------*/ $order_id = 123; $meta_key = 'mymetakey'; $meta_value = array( 'key1'=> 'a', 'key2'=> 'b'} /* or $meta_value = 'new value'; if you want */ $meta_id = wppizza_do_order_meta($order_id, $meta_key, $meta_value);
Deleting a specific metakey of Order
/*------------------------------------------------------------------------------ # $param int - order id # $param str - meta key we are deleting of this order # $returns bool ------------------------------------------------------------------------------*/ $order_id = 123; $meta_key = 'mymetakey'; $meta_id = wppizza_delete_order_meta($order_id, $meta_key');
Get metavalue of an Order for a specific metakey
/*------------------------------------------------------------------------------ # $param int - order id # $param str - meta key we are querying # $param bool - return value only # $returns mixed ------------------------------------------------------------------------------*/ $order_id = 123; $meta_name = 'mymetakey'; $meta_value_only = true; $res = wppizza_get_order_meta($order_id, $meta_name, $meta_value_only );
Deleting an order and its associated meta data by id/blogid
/*------------------------------------------------------------------------------ # $param int - order id # $param int - blog id (only relevant in mutisite setups). set blog id to distinctly target order of a specific blog, or false/omit for current blog # return void ------------------------------------------------------------------------------*/ /* multisite setups: */ $order_id = 123; $blog_id = 1; wppizza_delete_order($order_id, $blog_id); /* single site setup, simply do: */ $order_id = 123; wppizza_delete_order($order_id);
This is it for the time being, but if you have a particular query you need like help with and you cannot figure out , let me know and I’ll see what I can do
]]>Requires wppizza 3.3 (but might also work with slightly earlier versions) Note: the basics of this are tested, but further modifications will be required. Read the notes for each filter/action below. This might not work with pre-paid – i.e paid by credit card – orders (not tested). If it does not but you need this you will have to figure out a way to do this yourself as it’s really bad form to tell people you might not accept an order when it was already paid for (in my book anyway).
set an order to be unconfirmed first
example:
/***************************************************** * set an order to be unconfirmed ******************************************************/ add_action('wppizza_before_order_execute', 'myprefix_execute_as_unconfirmed'); /****************************************************** * intercepting "normal" execution of cod style orders * to set an order to "UNCONFIRMED" ******************************************************/ function myprefix_execute_as_unconfirmed($order){ /************************************************************ a made up $transaction_id as there is none yet but can be overridden when finally executing/confirming ************************************************************/ $order_initiator = $order['ordervars']['payment_gateway']['value']; $order_id = $order['ordervars']['order_id']['value']; $transaction_id = $order_initiator . WPPIZZA_WP_TIME . $order_id ; /************************************************************ $custom_update_columns - none ************************************************************/ $custom_update_columns = false; /************************************************************ $transaction_details - set some details if you want or need to refer to later or simply false ************************************************************/ //$transaction_details['my_prefix']['key'] = 'somekey'; $transaction_details = false; /************************************************************ $transaction_errors - set to false (as there cannot be any yet) ************************************************************/ $transaction_errors = false; /************************************************************ perhaps us __CLASS__ if script used in class - used as an identifier for logging purposes, or an arbitrary string if used outside class (no spaces or special chars other than "-" or "_" please though) ************************************************************/ $class_name = 'some_identifier'; /************************************************************ $check_user_id - should we check for user id too to make sure wp_user_id of order we are dealing with matches the current users wp_user_id ? in same cases this can be set, but if we are receiving notifications from a third party , this should be null - in fact, one should quite safely be able to keep it at null ************************************************************/ $check_user_id = null; /************************************************************ $unconfirmed - set to true here (that's the point of the plugin after all) ************************************************************/ $unconfirmed = true; /* if you want to send some other, customised emails instead, uncomment and create the function (here myprefix_send_confirmation_message) that sends your custom emails somehow */ //add_filter('wppizza_on_order_execute_send_email', array($this, 'myprefix_send_confirmation_message'), 10, 5); /************************************************************ $send_emails - do not send the standard confirmation emails ************************************************************/ $send_emails = false; /* execute (capture, omit sending standard emails, and set to UNCONFIRMED instead of complete) */ $result = wppizza_order_execute($order, $transaction_id, $transaction_details, $transaction_errors, $class_name, $check_user_id, $custom_update_columns, $unconfirmed, $send_emails); /* return errors if any, else redirect */ if(isset($result['error'])){ print"".json_encode($result).""; exit(); } /* $result will now be a redirection link and redirect to thank you page with UNCONFIRMED details (set in localization) */ print"".json_encode($result).""; exit();//we must exit here }
add a page reloader on unconfirmed results page
example:
add_filter('wppizza_filter_pages_unconfirmed_markup', 'myprefix_thankyou_page_unconfirmed_reload', 10, 2); function myprefix_thankyou_page_unconfirmed_reload($markup, $order_formatted){ if($order_formatted['ordervars']['payment_status']['value'] == 'UNCONFIRMED'){ $markup['myprefix_refresh_page']='<script>setInterval(function(){window.location = window.location.href;return;},5000);</script>';//reload page every 5 seconds } return $markup; }
accept an order programatically
example:
add_action('init', 'myprefix_accept_order'); /******************************************************* * * accept an order * typically done by some script in the backend sending * some post or get vars * YOU SHOULD ADD SOME MORE VERIFICATION HERE * THE BELOW IS JUST A SKELETON ******************************************************/ function myprefix_accept_order(){ /* a simple check that something was received AGAIN, YOU REALLY SHOULD ADD MORE VERIFICATION HERE */ if(empty($_REQUEST)){return;} /* parameters received, sanitised */ $parameters = wppizza_sanitize_post_vars($_REQUEST); /* we assume $parameters['id'] is the order id */ $order_id = $parameters['id']; /* check that received id matches an unconfirmed order by trying to get an unconfirmed order by order id and UNCONFIRMED status */ $columns = array(); $columns['id'] = array('data' => $order_id, 'operator' => '='); $columns['payment_status'] = array('data' => 'UNCONFIRMED', 'operator' => '='); $order = wppizza_get_order_by_columns($columns); /* bail if order not found */ if(empty($order)){return;} /******* assuming all is good - now execute the previously unconfirmed but now confirmed order sending emails , setting to completed etc etc ********/ $transaction_id = $order['sections']['ordervars']['transaction_id']['value'] ;//use tx id we have set previously $transaction_details = $parameters;// capture tx detals $transaction_errors = false;// there are no errors that can have happened (or script should have bailed earlier already) $class_name = 'some_identifier';// for logging, use __CLASS__ if used in calss, else some arbitrary string $check_user_id = false;// do not try and match user id as this script is called from somewhere else , not related to the user at this time) $custom_update_columns = false;// no additional column update required (unless you want to, check wppizza_order_execute_ipn as to how ) $unconfirmed = false;// false as we want to complete an order that's already set to unconfirmed /* now send normal emails etc etc */ $complete_order = wppizza_order_execute_ipn($order, $transaction_id, $transaction_details, $transaction_errors, $class_name, $custom_update_columns, $unconfirmed ); return; }]]>
alter the filepath and file contents as well as the recipient key according to your requirements.
@param: array (current attachments)
@param: str (recipient)
@param: array (email settings)
@param: array (formatted order details)
@param: array (unformatted order details)
@return: array
example:
/* add attachment */ add_filter('wppizza_filter_mail_attachments', 'my_prefix_my_add_attachment', 10, 5); function my_prefix_my_add_attachment( $wp_mail_attachments, $recipient_key, $email_settings, $order_formatted, $order_raw){ /* attaching a file to emails to the shop */ if($recipient_key == 'shop'){ $data = json_encode($order_formatted, JSON_PRETTY_PRINT);//some data to store $file_path = '/some/path/to/some/temp/file.json';//file path to the attachment file you will be sending file_put_contents($file_path, $data);//store the file $wp_mail_attachments[]=$file_path;//attach the file to email } return $wp_mail_attachments; }
perhaps wrap the unlink into a file_exist or something too. if you want to keep the file we created above, simply omit this action (you’ll probably want to name the file something more unique though, like using the order id available in the $order_formatted parameter)
@param: str (recipient key)
@return: void
example:
/* unlink attachment again after email was sent*/ add_action('wppizza_on_email_sent', 'my_prefix_my_unlink_attachment'); function my_prefix_my_unlink_attachment($recipient_key){ if($recipient_key == 'shop'){ $file_path = '/some/path/to/some/temp/file.json'; //path to the file we created above @unlink($file_path); //delete file after we're done with it } return; }]]>
WPPizza -> Reports
The sales report can be manipulated using a variety of filters/actions according to the examples below. Depending on your requirements, you might need to use one, more or all of them.
Removing columns from / adding columns to “Detailed” report export WPpizza->Reports
example:
/********************************************************** removing all "order verbose" details adding a custom column use print_r($columns) for all available column keys **********************************************************/ add_filter( 'wppizza_filter_csv_columns_detailed', 'myprefix_alter_report_columns' ); function myprefix_alter_report_columns($columns){ /* remove order_verbose column label */ unset($columns['order_verbose']); /* add custom column */ $columns['my_column'] = 'My Custom Column'; return $columns; } add_filter( 'wppizza_filter_csv_rows_detailed', 'myprefix_alter_report_rows', 10, 4 ); function myprefix_alter_report_rows($order, $values, $user_data, $oId){ /* remove order_verbose column data */ unset($order['order_verbose']); /* add custom column. adding some data based on $order or $values parameters for example */ $order['my_column'] = 'some data' ; return $order; }
Creating your own report and adding it to “WPPizza->Reports->Export” dropdown
example:
/********************************************************************* adding "My custom report" to report export dropdown options using 'myprefix_myreport' key *********************************************************************/ add_filter('wppizza_filter_csv_export_select', 'myprefix_export_name' ); function myprefix_export_name($array){ /* adding report with "myprefixmyreport" key to dropdown (key must be a-zA-Z0-9 only) */ $array['myprefixmyreport'] = 'My custom report'; return $array; }
/********************************************************** generating report for export when 'myprefixmyreport' was seleccted in dropdown **********************************************************/ add_filter('wppizza_filter_csv_export_myprefixmyreport', 'myprefix_report_export', 10 , 3 ); /********************************************************* * * [generating the csv] * * @param str * @param array * @param str * * @return str * * the below will generate exactly the same report as when using the "detailed" * option from the dropdown, so edit as required for your purposes *********************************************************/ function myprefix_report_export($csv, $data, $type){ /******************* # order data will always be grouped by blogs, even if only one blog and/or it's not a multisite setup # # (in a multisite setup orders from multiple blogs might be returned depending on settings # and additionally have different order form settings labels and/or counts) # # so we need to always loop through each blog (though there might only be one of course) *******************/ /***************** ini an empty array we implode later to the csv string *****************/ $csvData = array(); /***************** ini an empty array that will contain the csv rows of each blog *****************/ $csvBlogRows = array(); /***************** columns used per blog to add more empty separators if necessary when putting it all into a single csv *****************/ $columnCount = array(); /**************** # first of all, make sure there's actually some data returned ****************/ if(!empty($data['blogs'])){ foreach($data['blogs'] as $blogID => $blogInfo){ /* * * * * * * * # set top row - blog info * * * * * * * */ $blog_info = array(); $blog_info['blog_id'] = '"(Blog #'.$blogInfo['blog_id'].')"'; $blog_info['blogname'] = '"'.substr($blogInfo['blogname'], 0, 18 ).'"';//lets not have massive strings here //$blog_info['siteurl'] = substr($blogInfo['siteurl'], 0, 16 );// skip this for now. might mess up column widths and blogname should do really /* --------------------------- allow blog info filtering --------------------------- */ $blog_info = apply_filters('wppizza_filter_csv_bloginfo_'.$type.'', $blog_info, $blogInfo, $blogID); /***** max columns this blog *****/ $columnCountBlogInfo[$blogID] = count($blog_info); /***** convert bloginfo comma separated (to not mess up column widths too much) string *****/ $csvBlogRows[$blogID]['blog_info'] = implode(',', $blog_info); /* * * * * * * * * * * * * * * */ /* * * * * * * * # set second row - column labels * * * * * * * */ $columns = array(); /* order transaction details */ $columns['order_id'] = __('Order ID', 'wppizza_admin'); $columns['order_date_formatted'] = __('Date', 'wppizza_admin'); $columns['order_paid_by'] = __('Paid By', 'wppizza_admin'); $columns['payment_status'] = __('Status', 'wppizza_admin'); $columns['transaction_id'] = __('Transaction ID', 'wppizza_admin'); $columns['self_pickup'] = __('Pickup', 'wppizza_admin'); /* WP (un)-registered users */ $columns['user_registered'] = __('Registered User', 'wppizza_admin'); $columns['user_username'] = __('Username', 'wppizza_admin'); $columns['user_fullname'] = __('Full Name', 'wppizza_admin'); $columns['user_email'] = __('eMail', 'wppizza_admin'); /* customer info labels - entered in checkout page - related to each order looping through each formfield */ foreach($data['formfields'][$blogID] as $ffID => $ffValues){ $columns['customer_'.$ffID] = $ffValues['label']; } $columns['customer_ip_address'] = __('IP Address', 'wppizza_admin'); /* order items */ $columns['order_verbose'] = __('Order Verbose', 'wppizza_admin'); $columns['number_of_items'] = __('Products Count', 'wppizza_admin'); $columns['products_verbose'] = __('Products Verbose', 'wppizza_admin'); /* financials */ $columns['currencyiso'] = __('Currency', 'wppizza_admin'); $columns['total_price_items'] = __('Price Items', 'wppizza_admin'); $columns['total_discounts'] = __('Discounts', 'wppizza_admin'); $columns['delivery_charges'] = __('Delivery Charges', 'wppizza_admin'); $columns['handling_charges'] = __('Handling Charges', 'wppizza_admin'); $columns['tips'] = __('Tips', 'wppizza_admin'); $columns['tax_rates_verbose'] = __('Tax Rates', 'wppizza_admin'); $columns['taxes_included'] = __('Taxes Included', 'wppizza_admin'); $columns['taxes'] = __('Taxes', 'wppizza_admin'); $columns['total'] = __('Total', 'wppizza_admin'); /* --------------------------- allow column name filtering --------------------------- */ $columns = apply_filters('wppizza_filter_csv_columns_'.$type.'', $columns ); /***** max columns this blog *****/ $columnCount[$blogID] = count($columns); /***** convert column names to comma separated string and add linebreak *****/ $csvBlogRows[$blogID]['columns'] = implode(',', $columns); /* * * * * * * * * * * * * * * */ /* * * * * * * * loop through orders - matching values to column * * * * * * * */ $orders = array(); foreach($data['orders'][$blogID] as $oId => $values){ $order = array(); /* order transaction details */ $order['order_id'] = $oId ; $order['order_date_formatted'] = date('Y-m-d H:i:s', $values['order']['order_date_timestamp']); $order['order_paid_by'] = $values['order']['initiator']; $order['payment_status'] = $values['order']['payment_status']; $order['transaction_id'] = $values['order']['transaction_id']; $order['self_pickup'] = !empty($values['order']['self_pickup']) ? 'Y' : 'N'; /* WP (un)-registered users */ $user_id = $values['order']['wp_user_id'];//user id associated with this order $user_data = $data['users'][$user_id];//user date associated with this user id (if any) $order['user_registered'] = !empty($user_id) ? 'Y' : 'N'; $order['user_username'] = !empty($user_data) ? $user_data['user_login'] : ''; $order['user_fullname'] = !empty($user_data) ? $user_data['first_name'] . ' ' . $user_data['last_name'] : '' ; $order['user_email'] = !empty($user_data) ? $user_data['user_email'] : '' ; /* customer info labels - entered in checkout page - related to each order looping through each formfield make sure to wrap each line in quotes */ foreach($data['formfields'][$blogID] as $ffID => $ffValues){ $order['customer_'.$ffID] = $values['customer'][$ffID]; } $order['customer_ip_address'] = $values['customer']['ip_address']; /* order items */ $order['order_verbose'] = $values['order']['verbose']; $order['number_of_items'] = $values['order']['number_of_items']; $productsVerbose = array(); foreach($values['items'] as $iId => $item){ $productsVerbose[$iId] = $item['quantity'].'x '.$item['title'].' ['.$item['price_label'].'] - '.$item['pricetotal_formatted'] ; } $order['products_verbose'] = implode(PHP_EOL, $productsVerbose); /* financials */ $order['currencyiso'] = $values['order']['currencyiso']; $order['total_price_items'] = $values['order']['total_price_items']; $order['total_discounts'] = (0 - $values['order']['total_discounts']);//make negative $order['delivery_charges'] = $values['order']['delivery_charges']; $order['handling_charges'] = $values['order']['handling_charges']; $order['tips'] = $values['order']['tips']; $taxRatesVerbose = array(); if(!empty($values['order']['tax_by_rate'])){ foreach($values['order']['tax_by_rate'] as $taxType=>$rates){ $taxRatesVerbose[] = $taxType . ' @' . $rates['rate'].'%'; } } $order['tax_rates_verbose'] = implode(PHP_EOL, $taxRatesVerbose);//wrap in quotes to make sure linebreaks work $order['taxes_included'] = !empty($values['order']['tax_included']) ? 'Y' : 'N'; $order['taxes'] = $values['order']['taxes']; $order['total'] = $values['order']['total']; /* --------------------------- allow row data filtering --------------------------- */ $order = apply_filters('wppizza_filter_csv_rows_'.$type.'', $order, $values, $user_data, $oId ); /***** convert to comma separated string each value enclosed by quotes to make sure linebreaks are recognised using helper function to sanitise csv values *****/ $order = array_map('myhelper_sanitize_csv_values', $order); $orders[$oId] = '"'.implode('","', $order).'"'; } /***** join all orders adding linebreaks in between *****/ $csvBlogRows[$blogID]['orders'] = $orders; /* * * * * * * * * * * * * * * */ } } /************************************************************ create csv for each blog accounting for maximum columns per blog adding comma separators if necessary ************************************************************/ $maxColumns = max($columnCount); if(!empty($data['blogs'])){ foreach($data['blogs'] as $blogID => $blogInfo){ /* determine how many additional separators we need for each line of data of this blog */ $additionalSeparatorsBlogInfo = ($maxColumns - $columnCountBlogInfo[$blogID]); $additionalSeparatorsData = ($maxColumns - $columnCount[$blogID]); /* blog info */ $csvBlogRows[$blogID]['blog_info'] = $csvBlogRows[$blogID]['blog_info']. str_repeat(",", $additionalSeparatorsBlogInfo); /* columns */ $csvBlogRows[$blogID]['columns'] = $csvBlogRows[$blogID]['columns']. str_repeat(",", $additionalSeparatorsData); /* order data */ $orders = array(); foreach($csvBlogRows[$blogID]['orders'] as $oId => $order){ $orders[$oId] = $order . str_repeat(",", $additionalSeparatorsData); } $csvBlogRows[$blogID]['orders'] = implode(PHP_EOL, $orders); /******************************* implode data for this blogid *******************************/ $csvData[$blogID] = implode(PHP_EOL, $csvBlogRows[$blogID]); } } /* # * # * # * # * # * # * # * # * # * # * # * # * # * # # # implode data for all blogids to a single string, # for otput adding some linebreaks after each blog data # * # * # * # * # * # * # * # * # * # * # * # * # * # * # */ $lineBreaks = PHP_EOL . str_repeat(",", $maxColumns) . PHP_EOL . str_repeat(",", $maxColumns). PHP_EOL ; $csv = implode($lineBreaks, $csvData) . $lineBreaks; return $csv; }
/********************************************************* * * [sanitise csv values. just to make sure we have csv conform values * converting entities, removing commas and quotes * called before imploding order data to csv string ] * * @since 3.9 * @param str * @return str * *********************************************************/ function myhelper_sanitize_csv_values($value){ /* a - strip tags */ $value = wp_strip_all_tags($value); /* b - convert commas */ $value = str_replace(',',";", $value); /* c - convert quotes */ $value = str_replace('"',"`", $value); return $value; }
alter the query according to your requirements
@param: str (the whole query string)
@param: str (blog prefix)
@param: str (more or less the WHERE part of the query using the appropriate date ranges etc – just for convenience in some circumstances)
@return: str
example:
add_filter('wppizza_filter_report_query', 'my_prefix_my_query', 10, 3); function my_prefix_my_query($ordersQuery, $wpdbPrefix, $oQuery){ /* maybe not the most useful example but to keep it simple - look at the table structure of the wppizza_orders table to create a query appropriate to your scenario */ $ordersQuery = str_ireplace("WHERE", "WHERE wp_user_id = '5' AND ");/* keep the query as is, but only query sales from user with user_id 5 */ return $ordersQuery; }
modify the dataset array that will be passed on to the wppizza_report_export function and the wppizza_custom_report action below
@param: array (current dataset)
@param: array (order details returned for each order the query result includes)
@return: array
example:
add_filter('wppizza_filter_report_datasets', 'my_prefix_my_datasets', 10, 2); function my_prefix_my_datasets($datasets, $processOrder){ /* adding my_custom_dataset to already existing/default ones */ $datasets['my_custom_dataset'] = array(); $datasets['my_custom_dataset']['count'] = 0; /* a very basic example */ foreach($processOrder as $k=>$v){ /* use print_r($v) to get all array key/values associated with an order*/ $datasets['my_custom_dataset']['count'] ++; $datasets['my_custom_dataset'][$k]['value'] = 'some value for order with key '.$k.''; } return $datasets; }
modify the results (rows/columns etc) to be used in the csv file to export/save
@param: array ($result – array of csv parts/results to be included in report)
@param: array ($report_data – array of report_data including datasets)
@return: array
example:
add_action('wppizza_filter_reports_export_results', 'my_custom_reports_export_results'); function my_custom_reports_export_results($result, $report_data){ /* Check / vardump $result parameter to get array keys/values of the report some examples below - modify as required */ /* do NOT include the "sales value by order status" in csv */ unset($result['order_status_summary']); /* do NOT include the "sales value by gateway" in csv */ unset($result['sales_by_gateway']); /* do NOT include "sales by item" in csv */ unset($result['sales_by_item']); /* add 'my customised dataset' created by using wppizza_filter_report_datasets - see example above - to the report output */ $result['my_custom_dataset'] = '';// initialise the string $result['my_custom_dataset'] .= PHP_EOL . '"some label"'. PHP_EOL ; /* add header row */ /* add results rows */ foreach($report_data['dataset']['my_custom_dataset'] as $key=>$array){ $result['my_custom_dataset'] .= $array['value']; // add data row $result['my_custom_dataset'] .=PHP_EOL;// make sure to start a new line for each new row } $result['my_custom_dataset'] .=PHP_EOL . PHP_EOL; // add another couple of empty lines for clarity after the end of it all return $result; }
creating your own export report, completely REPLACING the whole function with your own
@param: array ($report_data)
@return: void
example:
as i starting point i would suggest the following
– copy the whole ‘wppizza_report_export’ function (located in classes/subpages/subpage.reports.php) as your ‘my_custom_report_export’ function.
– you must remove the action hook (do_action(‘wppizza_custom_report’, $report_data);) in that copy or you will have an infinite loop
– edit as required
add_action('wppizza_custom_report', 'my_custom_report_export'); function my_custom_report_export($report_data){ /* run your own reports functions using a copy of wppizza_report_export (see notes above), so it's something like: */ if(empty($_GET['export'])){ return; } $currency = $report_data['currency']; $dataset = $report_data['dataset'];/* $dataset will also now contain your $datasets['my_custom_dataset'] from above - do print_r($report_data to get the whole array) */ /* ... a lot more code .... */ header("Content-Length: " . strlen($result)); echo $result; exit();// dont forget to exit }
get csv report data as a string in a variable
@param: array (query arguments)
@return: string (as csv)
example:
$args = array( /* range of report data to retrieve. if 'from' or 'to' are omitted defaults to last 30 days */ 'range' => array( 'from' =>'2020-04-01', //from date in 'Y-m-d' format. Will always use time of 00:00:00 'to' =>'2020-04-15', //to date in 'Y-m-d' format. Will always use time of 23:59:59 ), /* defaults to 'detailed' if omitted. Should not be set to 'summary' (this will not work). Use above filters to filter the detailed report if you wish If you have created your own report using 'wppizza_filter_csv_export_select' and 'wppizza_filter_csv_export_{$key}' above use that type ($key) instead if you wish to retrieve the data of that report */ 'type' => 'detailed', ); /* return the csv data as a string in the $csv variable */ $csv = wppizza_reports_data($args); /* You can now use the data contained in '$csv' to - perhaps - save it to some file or save to file and email the report as attachment somewhere or do whatever it is you need to do ... If you wanted your code to run as a WP cronjob refer to the WordPress codex regarding scheduling wp_cron */]]>