cakephp probleme with pagination and file_get_contents - google-maps-api-3

I develop a back-end for a mobile application with cakephp
I have a function that list cities and I want to calculate distance from the user the this cities the code is:
$origins='origins=casablanca,maroc';
$destinations='&destinations=';
$url='http://maps.googleapis.com/maps/api/distancematrix/json?';
$this->paginate = array(
'limit' => 10,
'fields'=>array('cityId','cityFileName','cityName','stateId','stateFileName','stateName',
'countryCode','countryFileName','countryName','count(id) as num_hotels'),
'order' => 'num_hotels desc',
'group' =>array('cityId')
);
$hotels = $this->paginate();
for ($i = 0; $i < count($hotels); ++$i) {
$destination=($i==0?'':'|');
$destination.=$hotels[$i]['Hotel']['cityName'].','.$hotels[$i]['Hotel']['countryName'];
$destinations.=$destination;
}
$url.=$origins.$destinations.'&mode=driving&language=fr-FR&sensor=false';
$json = file_get_contents($url,0,null,null);
$details = json_decode($json, TRUE);
for ($i = 0; $i < count($hotels); ++$i) {
$hotels = Set::insert($hotels, $i.'.Hotel.distance',$details['rows']['0']['elements']['0']['distance']['value']);
}
$this->set(compact('hotels'));
$this -> viewPath = "hotels";
$this -> render("json/index","json/default");
the problem is when i test with the first page (pagination) the result is good but when i access to others page >=2 i got this warning and i cant get the distance
the error is :
Warning (2): file_get_contents(http://maps.googleapis.com/maps/api/distancematrix/json?origins=casablanca,maroc&destinations=Zagora,Morocco|Meknes,Morocco|Chefchaouen,Morocco|Tinghir,Morocco|M'hamid,Morocco|El Jadida,Morocco|Erfoud,Morocco|Skoura,Morocco|Tetouan,Morocco|Imlil,Morocco&mode=driving&language=fr-FR&sensor=false) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
[APP\Controller\ApiController.php, line 81]
Code Context
$origins = "origins=casablanca,maroc"
$destinations = "&destinations=Zagora,Morocco|Meknes,Morocco|Chefchaouen,Morocco|Tinghir,Morocco|M'hamid,Morocco|El
Jadida,Morocco|Erfoud,Morocco|Skoura,Morocco|Tetouan,Morocco|Imlil,Morocco"
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=casablanca,maroc&destinations=Zagora,Morocco|Meknes,Morocco|Chefchaouen,Morocco|Tinghir,Morocco|M'hamid,Morocco|El
Jadida,Morocco|Erfoud,Morocco|Skoura,Morocco|Tetouan,Morocco|Imlil,Morocco&mode=driving&language=fr-FR&sensor=false"
$hotels = array( array( "Hotel" => array(), array() ), array(
"Hotel" => array(), array() ), array( "Hotel" => array(), array()
), array( "Hotel" => array(), array() ), array( "Hotel" =>
array(), array() ), array( "Hotel" => array(), array() ), array(
"Hotel" => array(), array() ), array( "Hotel" => array(), array()
), array( "Hotel" => array(), array() ), array( "Hotel" =>
array(), array() ) ) $i = 10 $destination = "|Imlil,Morocco"
$http_response_header = array( "HTTP/1.0 400 Bad Request",
"Content-Type: text/html; charset=UTF-8", "Content-Length: 925",
"Date: Wed, 08 Aug 2012 15:42:43 GMT", "Server: GFE/2.0" )
file_get_contents - [internal], line ?? ApiController::yassine() -
APP\Controller\ApiController.php, line 81
ReflectionMethod::invokeArgs() - [internal], line ??
Controller::invokeAction() - CORE\Cake\Controller\Controller.php, line
473 Dispatcher::_invoke() - CORE\Cake\Routing\Dispatcher.php, line 104
Dispatcher::dispatch() - CORE\Cake\Routing\Dispatcher.php, line 86
[main] - APP\webroot\index.php, line 96

You must correct this line.
$url.="origins=" . urlencode($origins). "&destinations=" .
urlencode($destinations)."&mode=driving&language=fr-FR&sensor=false";

Related

Get a order data from Awebsite and create order on website B Woocoomerce API

I want to get product_id (from Website A ) Woocommerce APi and create a order in website B
If from Website A product_id =11 then create product_id= 1050 in website B
If product_id =121 then create product_id= 160 in website B
function create_order_from( $customer_id, $new_customer_data, $password_generated ) {
$live_ck = 'ck_blablabla';
$live_cs = 'cs_blablabla';
$live_url = 'https://www.website.com/wp-json/wc/v3/orders?consumer_key=' . $live_ck . '&consumer_secret=' . $live_cs;
$customer = new WC_Customer( $customer_id );
$body = array(
'status' => 'completed',
'meta_data' => array( array(
'key' => 'createdby',
'value' => 'website'
)),
'total' => 0,
'billing' => array(
'first_name' => $customer->get_billing_first_name(),
'email' => $customer->get_email(),
),
'line_items' => array( array(
'product_id' => 1050,
'quantity' => 1,
)),
);
$raw_response = wp_remote_post( $live_url,
array(
'headers' => array( 'Content-Type' => 'application/json' ),
'timeout' => 30,
'body' => json_encode( $body ),
)
);
}```
THank you for your help

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' );

query WooCommerce orders within a date range through a custom meta key

I have a meta_key called delivered_date, in date format, example 2021-05-13 16:01:26.
If I MUST use wc_get_orders( $args ), how can I get all orders within a date range?
Tried using the meta_compare argument but it returns nothing:
// The 2 variables below will come from a datepicker widget
$start_date = "2021-05-10 0:00:00";
$end_date = "2021-05-30 11:59:59";
$args = array(
'type' => 'shop_order',
'limit' => 100,
'paginate' => true,
'page' => 1,
'orderby' => 'id',
'order' => 'DESC',
'meta_key' => 'delivered_date',
'meta_value' => array($start_date, $end_date),
'meta_compare' => 'BETWEEN',
);
$result = wc_get_orders( $args );
You are close, use date — Format a local time/date
So you get:
// The 2 variables below will come from a datepicker widget
$start_date = date( '2021-05-10 00:00:00' );
$end_date = date( '2021-05-30 11:59:59' );
$args = array(
'orderby' => 'id',
'order' => 'DESC',
'meta_key' => 'delivered_date',
'meta_value' => array( $start_date, $end_date ),
'meta_compare' => 'BETWEEN',
);
$orders = wc_get_orders( $args );
// NOT empty
if ( ! empty ( $orders ) ) {
foreach ( $orders as $order ) {
echo '<p>ID = ' . $order->get_id() . '</p>';
}
}
Result: ID = 2525, ID = 2524, ID = 2523

Wordpress pre_get_posts and date_query showing blank screen

I'm trying to implement a filter on wp_query to show annual archives by School Year (sept - may) rather than jan-dec. When I view a yearly archive page, such as sitename.com/2017/, I get a white screen of death, and no PHP errors.
My code in functions.php looks like the following:
add_action( 'pre_get_posts', 'school_year_filter' );
function school_year_filter($query) {
if (! is_admin() && $query->is_main_query() && $query->is_year() && $query->is_archive()) {
$year = get_query_var('year');
$year2 = $year + 1;
$query->set(
'date_query' => array(
array(
'after' => array(
'year' => "$year",
'month' => '9',
'day' => '1',
),
'before' => array(
'year' => "$year2",
'month' => '5',
'day' => '31',
),
'inclusive' => true,
),
),
);
}
}
Try this code.
I changed this line 'date_query'=>array( to 'date_query', array(.
add_action( 'pre_get_posts', 'school_year_filter' );
function school_year_filter($query) {
if (! is_admin() && $query->is_main_query() && $query->is_year() && $query->is_archive()) {
$year = get_query_var('year');
$year2 = $year + 1;
$query->set(
'date_query', array(
array(
'after' => array(
'year' => $year,
'month' => '9',
'day' => '1',
),
'before' => array(
'year' => $year2,
'month' => '5',
'day' => '31',
),
'inclusive' => true,
),
)
);
}
}
https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts#Only_Display_Search_Results_After_Specific_Date

Group results if meta_value is the same

I would like to group the results of my query if the meta_value is the same for any results. I would expect an output like this:
Group 1
- 1111
- 1111
- 1111
Group 2
- 1234
- 1234
Here is my query:
$args = array(
'post_type' => 'product-api',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'last_updated',
'value' => '',
'compare' => '!=',
)
),
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$count++;
$the_query->the_post();
$model = get_post_meta(get_the_id(), 'product_model', true);
echo $model;
}
}
wp_reset_postdata();
What would be the best approach to achieve this?

Resources