Uncaught Error: Call to undefined function wc_get_orders() - wordpress

I'm trying to get my orders via wc_get_orders() from Woocommerce orders. But while trying this, I got the error 'Uncaught error: call to undefined function wc_get_orders()' and I don't know what happened here. My code says the following:
if(isset($_GET['inicio']) ){
$initial_date = $_GET['inicio'];
$final_date = $_GET['fin'];
$orders = wc_get_orders(array(
'limit'=>-1,
//'type'=> 'shop_order',
'orderby' => 'date',
'order' => 'DESC',
'status'=> array( 'wc-processing' ),
'date_created'=> $initial_date .'...'. $final_date,
'return' => 'ids',
));/**/
$fechas="de ".$initial_date." a ".$final_date;
}else{
$orders = wc_get_orders(array(
'limit' => 10,
'orderby' => 'date',
'order' => 'DESC',
'status'=> array( 'wc-processing' ),
'return' => 'ids',
));
$fechas="(ultimos 10)";
}
I'm trying to get my orders details via wc_get_orders() from Woocommerce orders.
Additional info: complete code is>>
<?php
global $wpdb;
$host_name = $wpdb->dbhost;
$database = $wpdb->dbname;
$user_name = $wpdb->dbuser;
$password = $wpdb->dbpassword;
/*conectar bdd WP*/$link = mysqli_connect($host_name, $user_name, $password, $database);
if ($link->connect_error) {die("Connection failed: ". $link->connect_error);}else{/* echo "Connected successfully";/**/}
/*character set to utf8mb4 */$link->set_charset("utf8mb4");
//*
if(isset($_GET['inicio']) ){
$initial_date = $_GET['inicio'];
$final_date = $_GET['fin'];
$orders = wc_get_orders(array(
'limit'=>-1,
//'type'=> 'shop_order',
'orderby' => 'date',
'order' => 'DESC',
'status'=> array( 'wc-processing' ),
'date_created'=> $initial_date .'...'. $final_date,
'return' => 'ids',
));/**/
$fechas="de ".$initial_date." a ".$final_date;
}else{
$orders = wc_get_orders(array(
'limit' => 10,
'orderby' => 'date',
'order' => 'DESC',
'status'=> array( 'wc-processing' ),
'return' => 'ids',
));
$fechas="(ultimos 10)";
}
//$meta = "...<pre>".var_dump($orders)."</pre>...";
$meta="";
$pedidos=array();
$productos=array();//hay que guardar pedidos y clientes para hacer esa matriz
//$clientes=array();
// Loop through each WC_Order object
foreach( $orders as $order ){
$fecha=0;
$dia=0;
$planoNumero=0;
$planoLetra=0;
$latitud=0;
$longitud=0;
$nombre=0;
$tel=0;
$direccion=0;
$barrio=0;
$monto=0;
$envio=0;
$total=0;
$descuento=0;
$notas=0;
$formaPago=0;
$primera=0;
$marca=0;
$precio=1;
$meta.= $order . ' - '; // The order ID
//https://www.businessbloomer.com/woocommerce-easily-get-order-info-total-items-etc-from-order-object/
// Get $order object from order ID
$orderid = wc_get_order( $order );
// Now you have access to (see above)...
if ( $orderid ) {//verifica
//$meta.="...<pre>".var_dump($orderid)."</pre>...";
//objeto a array, es otra forma de traer datos
$order2 = json_decode(wc_get_order( $order ),true);
$meta.= $order2["status"]. ' - '.$order2["total"]." - "; // The order ID
// Datos del usuario
$user = $orderid->get_user();
//$meta.="...<pre>".var_dump($user)."</pre>...";
$userid=$user->ID;
$meta.= $userid." username: ".$user->user_nicename." - ";
$meta.= "plano numero: ".get_user_meta($userid ,'plano_numero',true)." - ";
$meta.= "plano letra: ".get_user_meta($userid ,'plano_letra',true)." - ";
$meta.= "latitud: ".get_user_meta($userid ,'latitud',true)." - ";
$meta.= "longitud: ".get_user_meta($userid ,'longitud',true)." - ";
$planoNumero=get_user_meta($userid ,'plano_numero',true);
$planoLetra=get_user_meta($userid ,'plano_letra',true);
$latitud=get_user_meta($userid ,'latitud',true);
$longitud=get_user_meta($userid ,'longitud',true);
if($planoLetra == ''){
$primera="SI";
}else{
$primera="NO";
}
/**/
//Datos de la orden
$meta.= $orderid->billing_entrega." dia entrega - ";
$meta.= $orderid->get_billing_first_name()." ".$orderid->get_billing_last_name();
$meta.=$orderid->get_date_created();
$meta.=$orderid->get_date_modified();
$meta.=$orderid->get_date_completed();
$meta.=$orderid->get_date_paid();
$fecha=$order2["date_created"]["date"];
$dia=$orderid->billing_entrega;
$nombre=$orderid->get_billing_first_name()." ".$orderid->get_billing_last_name();
//$clientes[]=$nombre;
$tel=$order2["billing"]["phone"];
$direccion=$orderid->shipping_first_name." ".$orderid->shipping_last_name.", ".$orderid->shipping_address_1." ".$orderid->shipping_address_2.", ".$orderid->shipping_city.", ".$orderid->shipping_state.", ".$orderid->shipping_postcode." ".$orderid->shipping_country;//sacando como objeto
//$direccion=$orderid->get_address('shipping'); //la trae como objeto
$direccion=$order2["shipping"]["first_name"]." ".$order2["shipping"]["last_name"]." / ".$order2["shipping"]["address_1"]." ".$order2["shipping"]["address_2"]." / ".$order2["shipping"]["city"]." / ".$order2["shipping"]["state"]." / ".$order2["shipping"]["postcode"]." ".$order2["shipping"]["country"];//o lo puedes sacar así como array
$monto=$order2["total"]-$order2["shipping_total"];
$envio=$order2["shipping_total"];
$total=$order2["total"];
$descuento=$order2["discount_total"];
$notas=$order2["customer_note"];
$formaPago=$order2["payment_method_title"];
//trae el barrio de la tabla segun cp
$cp=$order2["shipping"]["postcode"];
$sql="SELECT * FROM 0_cp_jo WHERE cp='".$cp."' LIMIT 1;";
$ejecutarquery=mysqli_query($link,$sql);
if(mysqli_num_rows($ejecutarquery)>0){
$row=mysqli_fetch_assoc($ejecutarquery);
$barrio=$row['barrio'];
}else{
$barrio=$cp." c.p. no encontrado";
}
/**/
// Get and Loop Over Order Items
$meta.= "<br>";
$congelados=0;
$lacteos=0;
$huerta=0;
foreach ( $orderid->get_items() as $item_id => $item ) {
//$meta.="...<pre>".var_dump($item)."</pre>...";
//Datos producto
$meta.= $item->get_product_id();
$meta.= " - ".$item->get_name();
$meta.= " - ".$item->get_quantity();
$producto=$item->get_name();
$qty=$item->get_quantity();
//terminos producto, categorias en este caso
$categorias=array();//se busca con in_array() para hacer tabla por categoria
$terms = get_the_terms ( $item->get_product_id(), 'product_cat' );
//$meta.="...<pre>".var_dump($terms)."</pre>...";
foreach ( $terms as $term ) {
$meta.= " - Categoria: ".$term->name;
$categoria=$term->name;
$categorias[]=$categoria;
//almacen es todos los productos disque en orden alfabetico
if($categoria=="congelados"){$congelados++;}
if($categoria=="Lácteos"){$lacteos++;}
if($categoria=="Frutas y Verduras"){$huerta++;}
}
//atributos del producto como marca
$product = wc_get_product( $item->get_product_id() );
$marca=$product->get_attribute( 'Marca' );
//el precio
$precio=$product->get_price();
$precio=$orderid->get_item_total( $item );;
$productos[]=array(
"orden"=>$order,
"cliente"=>$nombre,
"producto"=>$producto,
"qty"=>$qty,
"precio"=>$precio,
"marca"=>$marca,
"categorias"=>$categorias);
$meta.= "<br>";
}
}
$meta.= "<br>";
$meta.= "<br>";
//guardamos el pedido como un array para el echo mas adelante con un feach
$pedidos[]=array(
"fecha"=>$fecha,
"dia"=>$dia,
"orden"=>$order,
"congelados"=>$congelados,
"lacteos"=>$lacteos,
"huerta"=>$huerta,
"plano_numero"=>$planoNumero,
"plano_letra"=>$planoLetra,
"latitud"=>$latitud,
"longitud"=>$longitud,
"nombre"=>$nombre,
"tel"=>$tel,
"direccion"=>$direccion,
"barrio"=>$barrio,
"monto"=>$monto,
"envio"=>$envio,
"total"=>$total,
"descuento"=>$descuento,
"notas"=>$notas,
"forma_pago"=>$formaPago,
"primera"=>$primera);
//poner productos o clientes en orden alfabetico en el array, mejor clientes hace una diagonal casi
}
function eliminar_acentos($cadena){
//Reemplazamos la A y a
$cadena = str_replace(
array('Á', 'À', 'Â', 'Ä', 'á', 'à', 'ä', 'â', 'ª'),
array('A', 'A', 'A', 'A', 'a', 'a', 'a', 'a', 'a'),
$cadena );
//Reemplazamos la E y e
$cadena = str_replace(
array('É', 'È', 'Ê', 'Ë', 'é', 'è', 'ë', 'ê'),
array('E', 'E', 'E', 'E', 'e', 'e', 'e', 'e'),
$cadena );
//Reemplazamos la I y i
$cadena = str_replace(
array('Í', 'Ì', 'Ï', 'Î', 'í', 'ì', 'ï', 'î'),
array('I', 'I', 'I', 'I', 'i', 'i', 'i', 'i'),
$cadena );
//Reemplazamos la O y o
$cadena = str_replace(
array('Ó', 'Ò', 'Ö', 'Ô', 'ó', 'ò', 'ö', 'ô'),
array('O', 'O', 'O', 'O', 'o', 'o', 'o', 'o'),
$cadena );
//Reemplazamos la U y u
$cadena = str_replace(
array('Ú', 'Ù', 'Û', 'Ü', 'ú', 'ù', 'ü', 'û'),
array('U', 'U', 'U', 'U', 'u', 'u', 'u', 'u'),
$cadena );
//Reemplazamos la N, n, C y c
$cadena = str_replace(
array('Ñ', 'ñ', 'Ç', 'ç'),
array('N', 'n', 'C', 'c'),
$cadena
);
//como exportas csv que no haya comas
$cadena = str_replace(
array(','),
array(' '),
$cadena
);
return $cadena;
}
This file is located in /wp-admin/ folder

The problem is that you don't call your script in the Wordpress environment. So, you need to initialize Wordpress first.
Put this at the beginning of your php file:
/* Initialize Wordpress */
define( 'BASE_PATH', find_wordpress_base_path()."/" );
define( 'WP_USE_THEMES', false );
global $wp, $wp_query, $wp_the_query, $wp_rewrite, $wp_did_header;
require(BASE_PATH . 'wp-load.php');
function find_wordpress_base_path() {
$dir = dirname(__FILE__);
do {
//it is possible to check for other files here
if( file_exists($dir."/wp-config.php") ) {
return $dir;
}
} while( $dir = realpath("$dir/..") );
return null;
}
/* Restrict access to admin only */
if( ! current_user_can( 'administrator' )) return;
/* Now run your script here ... */
I would recommend running your script via a cronjob or putting your script into a shortcode, put the shortcode on a private page and then call that page. Then, you don't need the first part.

Related

WooCommerce | Customer's total spend on completed orders in a given time period

The code below is said to give the total spent spent over 30 days (if I'm not mistaken). But in my test, it calculates for the current month. How can I not update this code for last 6 months(180 days). The important thing is to be able to easily change the coverage day and make the calculation for the completed orders. Thanks.
Code resource:https://github.com/anaymark/woocommerce-monthly-spent-by-user/blob/master/total-spent-month-by-user.php
function total_spent_for_user_30days( $user_id=null ) {
if ( empty($user_id) ){
$user_id = get_current_user_id();
}
$today_year = date( 'Y' );
$today_month = date( 'm' );
$day = date( 'd' );
if ($today_month == '01') {
$month = '12';
$year = $today_year - 1;
} else{
$month = $today_month - 1;
$month = sprintf("%02d", $month);
$year = $today_year - 1;
}
// ORDERS FOR LAST 30 DAYS (Time calculations)
$now = strtotime('now');
$gap_days = 30;
$gap_days_in_seconds = 60*60*24*$gap_days;
$gap_time = $now - $gap_days_in_seconds;
$args = array(
'post_type' => 'shop_order',
'post_status' => array( 'wc-completed' ),
// all posts
'numberposts' => -1,
// for current user id
'meta_key' => '_customer_user',
'meta_value' => $user_id,
'date_query' => array(
//orders published on last 30 days
'relation' => 'OR',
array(
'year' => $today_year,
'month' => $today_month,
),
array(
'year' => $year,
'month' => $month,
),
),
);
// GET ALL ORDERS
$customer_orders = get_posts( $args );
$count = 0;
$total = 0;
$no_orders_message = __('No orders this month.', 'mytheme');
if (!empty($customer_orders)) {
$customer_orders_date = array();
foreach ( $customer_orders as $customer_order ){
$customer_order_date = strtotime($customer_order->post_date);
// PAST 30 DAYS
if ( $customer_order_date > $gap_time ) {
$customer_order_date;
$order = new WC_Order( $customer_order->ID );
$order_items = $order->get_items();
$total += $order->get_total();
// Going through each current customer items in the order
foreach ( $order_items as $order_item ){
$count++;
}
}
}
$monthly_spent_by_user = floatval( preg_replace( '#[^\d.]#', '', $total, $count ) );
return $monthly_spent_by_user;
} else {
return $no_orders_message;
}
}
add_shortcode( 'spent-last-month', 'total_spent_for_user_30days' );

Woo-commerce Booking - Fetch all available bookings based on Time Range

I'm trying to fetch bookings based on time availability in wocommerce bookings by passing the time selection in below format:
2019-08-26 08:00 - 2019-08-26 11:00
$available_blocks = $booking_form->product->get_available_blocks( array(
'blocks' => $blocks_in_range,
'from' => $from,
'to' => $to));
foreach ( $available_blocks as $check ) {
if ( true === $booking_form->product->check_availability_rules_against_date( $check, '' )){
//Custom Added to fetch only blocks in selected range
if( $from >= reset($available_blocks) && $to <= end($available_blocks)){
$matches[] = $post_id;
break; // check passed
}
}
}
But, it's only working when I pass time in Hour only format(10:00 AM), When I add minute(10:30 AM) it is not returning any available bookings.
Full function for reference.
/**
* Get all available booking products
*
* #param string $start_date_raw YYYY-MM-DD format
* #param string $end_date_raw YYYY-MM-DD format
* #param int $quantity Number of people to book
* #param string $behavior Whether to return exact matches
* #return array Available post IDs
*/
function get_available_bookings( $start_date_raw, $end_date_raw, $quantity = 1, $behavior = 'default' ) {
$matches = array();
// Separate dates from times
$start_date = explode( ' ', $start_date_raw );
$end_date = explode( ' ', $end_date_raw );
// If time wasn't passed, define defaults.
if ( ! isset( $start_date[1] ) ) {
$start_date[1] = '00:00';
}
$start = explode( '-', $start_date[0] );
$args = array(
'wc_bookings_field_resource' => 0,
'wc_bookings_field_persons' => $quantity,
'wc_bookings_field_duration' => 1,
'wc_bookings_field_start_date_year' => $start[0],
'wc_bookings_field_start_date_month' => $start[1],
'wc_bookings_field_start_date_day' => $start[2],
);
// Loop through all posts
foreach ( $this->product_ids as $post_id ) {
if ( 'product' == get_post_type( $post_id ) ) {
$product = wc_get_product( $post_id );
if ( is_wc_booking_product( $product ) ) {
// Grab the duration unit
$unit = $product->is_type( 'accommodation-booking' ) ? 'night' : $product->get_duration_unit();
// Support time
if ( in_array( $unit, array( 'minute', 'hour' ) ) ) {
if ( ! empty( $start_date[1] ) ) {
$args['wc_bookings_field_start_date_time'] = $start_date[1];
}
}
if ( 'exact' === $behavior ) {
$duration = $this->calculate_duration( $start_date_raw, $end_date_raw, $product->get_duration(), $unit );
$args['wc_bookings_field_duration'] = $duration;
}
$booking_form = new WC_Booking_Form( $product );
$posted_data = $booking_form->get_posted_data( $args );
// All slots are available (exact match)
if ( true === $booking_form->is_bookable( $posted_data ) ) {
$matches[] = $post_id;
}
// Any slot between the given dates are available
elseif ( 'exact' !== $behavior ) {
$from = strtotime( $start_date_raw );
$to = strtotime( $end_date_raw );
$blocks_in_range = $booking_form->product->get_blocks_in_range( $from, $to );
// Arguments changed in WC Bookings 1.11.1
$available_blocks = $booking_form->product->get_available_blocks( array(
'blocks' => $blocks_in_range,
'from' => $from,
'to' => $to
) );
foreach ( $available_blocks as $check ) {
if ( true === $booking_form->product->check_availability_rules_against_date( $check, '' )){
$matches[] = $post_id;
break; // check passed
}
}
}
}
}
}
return $matches;
}

How to limit query in price filter

How to limit query to 6 in woocommerce product price filter short-code [products_by_price min="100" max="300"]? The code below is based on woocommerce product short-code which unfortunately does not support per_page. In this case I need to limit query to 6 to avoid showing all products.
add_shortcode( 'wc_products_price_range', 'wc_products_price_range' );
function wc_products_price_range( $atts, $content, $shortcode ) {
if ( class_exists( 'WooCommerce' ) ) {
$shortcodes = new WC_Shortcodes();
if ( is_array( $atts ) ) {
$min = (int) $atts['min'];
$max = (int) $atts['max'];
if ( $min && $max ) {
$and = "meta_value BETWEEN $min AND $max";
} else {
if ( $min ) {
$and = "meta_value >= $min";
} elseif ( $max ) {
$and = "meta_value <= $max";
}
}
if ( $and ) {
global $wpdb;
$query = "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_price' AND $and";
$ids = $wpdb->get_col( $query );
if ( ! empty( $ids ) ) {
$atts['ids'] = implode( ",", $ids );
}
}
}
return $shortcodes->products( $atts );
}
}
After a quick scan of WC shortcode class I have came across this :
public static function products( $atts ) {
$atts = shortcode_atts( array(
'columns' => '4',
'orderby' => 'title',
'order' => 'asc',
'ids' => '',
'skus' => ''
), $atts );
it means you can pass 'column' attribute along with ids where you can limit posts per page.
and in this query :
$query = "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_price' AND $and";
you can use limit 0,6 with order by clause.
Hope this helps.
OR
random rows:
SELECT * FROM `table` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` ) ORDER BY id LIMIT 1;
or you can pass 'rand' to attributes in shortcode.

wordpress - Sortable custom fields columns

I added some custom fields (dates) in my admin columns. I try to make them sortable but in order to do that I need to convert them from string to date. My naive and simple code obviously doesn't work... Can someone point out my error(s) ?
add_action( 'pre_get_posts', 'orderby_date' );
function orderby_date( $query ) {
$orderby = $query->get( 'orderby');
if( 'start' == $orderby ) {
$query->set('meta_key','class_start');
$query->set('orderby',"STR_TO_DATE(meta_value,'%m/%d/%Y')");
}
}
This is what you are looking for:
add_filter( 'posts_clauses', 'manage_wp_posts_be_qe_posts_clauses', 1, 2 );
function manage_wp_posts_be_qe_posts_clauses( $pieces, $query ) {
global $wpdb;
if ( $query->is_main_query() && ( $orderby = $query->get( 'orderby' ) ) ) {
$order = strtoupper( $query->get( 'order' ) );
if ( ! in_array( $order, array( 'ASC', 'DESC' ) ) )
$order = 'ASC';
switch( $orderby ) {
case 'class_start':
$pieces[ 'join' ] .= " LEFT JOIN $wpdb->postmeta wp_rd ON wp_rd.post_id = {$wpdb->posts}.ID AND wp_rd.meta_key = 'class_start'";
$pieces[ 'orderby' ] = "STR_TO_DATE( wp_rd.meta_value,'%m/%d/%Y' ) $order, " . $pieces[ 'orderby' ];
break;
}
}
return $pieces;
}
You can read more about it here: http://wpdreamer.com/2014/04/how-to-make-your-wordpress-admin-columns-sortable/

Wordpress query with multiple meta meta keys

Can someone tell me what wrong with this query.
if ( isset( $_GET['lokacija'] ) && !empty( $_GET['lokacija'] ) ) {
$lokacija = $_GET['lokacija'];
} else { $lokacija = ''; }
if ( isset( $_GET['tip'] ) && !empty( $_GET['tip'] ) ) {
$tip = $_GET['tip'];
} else { $tip = ''; }
if ( isset( $_GET['sobe'] ) && !empty( $_GET['sobe'] ) ) {
$sobe = $_GET['sobe'];
} else { $sobe = ''; }
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args2 = array(
'posts_per_page' => 10,
'post_type' => 'nekretnine',
'paged' => $paged,
if ($lokacija != '') {
'meta_query' => array(
array (
'key' => 'lokacija',
'value' => $lokacija.''
),
)
}
);
$wp_query = new WP_Query( $args2 );
This code gives me error
Parse error: syntax error, unexpected T_IF, expecting ')' in
*/wp-content/themes/gs/page-nek-pretraga.php on line 23;
Line 23 is line that starts with if ($lokacija)...
What i want to do is to use multiple meta_query that i can get from php get (www.blabla./com/page1/?lokacija=foo&tip=foo&sobe=3)
But, i want it only if lets say $lokacija is not empty. Same for other two (possible 5-6 later) fields.
You can not include if condition in array. Whatever you are trying to achieve with above code is you can achieve with this following code.
$args2 = array(
'posts_per_page' => 10,
'post_type' => 'nekretnine',
'paged' => $paged,
);
if ($lokacija != '') {
$args2['meta_query'] = array(
array (
'key' => 'lokacija',
'value' => $lokacija.''
),
);
}
To check for multiple custom fields we have to join the meta table twice.
So the copy of the table is joined with a different temporary table name.
global $wpdb; $query = " SELECT * FROM {$wpdb--->prefix}posts
INNER JOIN {$wpdb->prefix}postmeta m1
ON ( {$wpdb->prefix}posts.ID = m1.post_id )
INNER JOIN {$wpdb->prefix}postmeta m2
ON ( {$wpdb->prefix}posts.ID = m2.post_id )
WHERE
{$wpdb->prefix}posts.post_type = 'post'
AND {$wpdb->prefix}posts.post_status = 'publish'
AND ( m1.meta_key = 'date' AND m1.meta_value > '2010-12-05 00:00:00' )
AND ( m1.meta_key = 'date' AND m1.meta_value < '2010-12-12 00:00:00' ) AND ( m2.meta_key = 'some_other_meta_value' AND m2.meta_value != '' ) GROUP BY {$wpdb->prefix}posts.ID
ORDER BY {$wpdb->prefix}posts.post_date
DESC;
For More Details Visit : http://realtuts.com/write-custom-wordpress-sql-query-multiple-meta-values/
";

Resources