Reitrac Reitrac - 12 days ago 97
Twig Question

SQL query to Twig

I have a WordPress with the last version.
I'm using "All in one calendar" by time.ly and I would like, for each event, return the end date by using SQL query. (i dont want to use {{event.end}}).

First, I'm overriding the function for the twig file :

add_filter( 'ai1ec_theme_args_agenda-widget.twig', 'mytheme_agenda_widget_args', 10, 2 );

function mytheme_agenda_widget_args( $args, $is_admin ) {
global $wpdb;
date_default_timezone_set('Europe/Paris');
foreach ( $args['dates'] as $date => &$date_info ) {
foreach ( $date_info['events'] as &$category ) {
foreach ( $category as &$event ) {
$post_id = $event->get( 'post_id' );
$sql = "SELECT end FROM og2rm_ai1ec_event_instances WHERE post_id = ".$post_id." ORDER BY id DESC ;";
$results = $wpdb->get_results($sql);
$end_date = strftime('%d %b', $results[0]->end);

$args['custom_field'] = array("post_id" => $post_id, "end_date" => $end_date);

echo "<pre>";
print_r($args['custom_field']);
echo "</pre>";
}
}
}
return $args;
}


My echo pre return :

Array
(
[post_id] => 21451
[end_date] => 13 Nov
)

Array
(
[post_id] => 21438
[end_date] => 09 Dec
)

Array
(
[post_id] => 21389
[end_date] => 13 Nov
)

Array
(
[post_id] => 21438
[end_date] => 09 Dec
)

Array
(
[post_id] => 21438
[end_date] => 09 Dec
)
[••••]


But when I'm using my variable
{{ custom_field.end_date }}
in my twig file, only the last value of my foreach returned for every event ...

Some one have an idea ?

Thanks.

Answer Source

The problem lies in the following line:

$args['custom_field'] =  array("post_id" => $post_id, "end_date" => $end_date);

You are overwriting the variable in each loop. The echo does not care because it runs inside the loop, but the return only gets the last value.

You might want to do something like this:

$args['custom_field'][] = array("post_id" => $post_id, "end_date" => $end_date);

or maybe:

 $args['custom_field'][$post_id] = array("post_id" => $post_id, "end_date" => $end_date);

You could also improve your code by moving the SQL-query outside the loop and using something like WHERE post_id IN (?) where ? is a comma separated list of post_ids. Then you will only send one query and you will get all post_id's and end date's as result from the query instead of fetching them one by one.