categories the posts month wise in wordpress? - php

i am trying to retrieve the last 8 months posts in wordpress. i have used following code to do this
$args = array(
'posts_per_page' => -1,
'date_query' => array(
array(
'column' => 'post_date_gmt',
'after' => '5 month ago',
)
)
);
$query = new WP_Query( $args );
Now i am wanted to place each month posts in separate array so that i can show them month wise in front-end.
Any idea about this ??

You can use a for loop:
$date = date('Y-m-d');
$dateArray = array();
$dateArray[] = $date;
for($i=1; $i<8 ; $i++){
$month = '- ' . $i . 'month';
$old_date = strtotime ( $month , strtotime ( $date ) ) ;
$old_date = date('Y-m-d', $old_date);
$dateArray[] = $old_date;
}
foreach($dateArray as $item){
$month_loop = date("m", strtotime($item));
$year_loop = date("Y", strtotime($item));
$query = new WP_Query('year=' . $year_loop . '&monthnum=' . $month_loop );
// Do action
}
I think it help to you

Related

Count Posts Between Dates

I use a few ACF date fields to basically provide start and end dates for posts, I need to be able to display how many posts are starting in the current month and ending in the current month, this is what I have so far, this doesn't provide the accurate count, not sure what's wrong with this and if it could be simplified. I have confirmed the function portion below is working correctly.
function getBetweenDates($startDate, $endDate) //array of dates for current month
{
$rangArray = [];
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
for ($currentDate = $startDate; $currentDate <= $endDate;
$currentDate += (86400)) {
$date = date('Y-m-d', $currentDate);
$rangArray[] = $date;
}
return $rangArray;
}
$this_month = getBetweenDates(date("Y-m-01"), date("Y-m-t"));
$posts = get_posts(array(//start dates this month
'post_type' => 'project',
'meta_key' => 'landlord_delivery_date',
'meta_value' => $this_month,
'meta_compare' => 'IN',
));
$fpposts = get_posts(array(//end dates this month
'post_type' => 'project',
'meta_key' => 'first_patient_date',
'meta_value' => $this_month,
'meta_compare' => 'IN',
));
$count = count($posts);//count ll dates
$fpcount = count($fpposts);//count fp dates```

Order created time difference

I found that code here and I'm wondering how can I add example: if order created time > order created time + 5 minutes?
Now code just check today datetime and order created datetime and make datediff, but I want to make time diff.
If someone can help me, thanks already!
function myplugin_cancel_unpaid_wc_orders() {
global $myplugin_options;
$my_cancel_time = $myplugin_options['myplugin_cancel_time'];
//$date = date( "Y-m-d H:i:s", strtotime( '-' . absint( $myplugin_cancel_time ) . ' MINUTES', current_time( 'timestamp' ) ) );
$query = ( array(
'limit' => 5,
'orderby' => 'date',
'order' => 'DESC',
'status' => array( 'pending' )
) );
$orders = wc_get_orders( $query );
foreach ( $orders as $order ) {
$date = new DateTime( $order->get_date_created() );
$today = new DateTime();
$interval = $date->diff($today);
$datediff = $interval->format('%a');
if ( $datediff >= 4 ) {
$order->update_status('cancelled', 'Cancelled for missing payment');
}
}
}
Convert the order created date to seconds. 5 minutes equal 300 seconds.
$order_created_date = $order->get_date_created(); // Get order date created WC_DateTime Object
$order_created_seconds = $order_created_date->getTimestamp(); // Get order create date in seconds
$end_time = $order_created_seconds+300; // Order created time + 5mins
$current_time = time();
if ($current_time >= $end_time) { // Check if end time
$order->update_status('cancelled', 'Cancelled for missing payment');
}

Can't get globals variable to work, how to pass the value from template to function in functions.php

Edited:
Problem is that when doing ajax loading of more posts the $year1 or $year value gets repeated. The value of $year is actually a month.
How it looks now:
December
Event 1
November
Event 2
Event 3
November--- here the ajax call happens and the month value gets repeated
Event 4
Event 5
Event 6
and How it should be:
December
Event 1
November
Event 2
Event 3
Event 4
Event 5
Event 6
I have so far tried with globals variables
Get a variable from one wordpress template file to another
and get query variables
https://wordpress.stackexchange.com/questions/96312/get-query-var-vs-global-query-variables
Another problem is that the date in functions.php returns the values in english, while the same code returns the date in spanish
in the template.
Code in template: Do note I used the $test variable with November value for testing porpuses, but it should be $year1
I don't know what I am doing wrong...
$my_posts = new WP_Query( $args );
if ( $my_posts->have_posts() ) :
?>
<div class="my-posts2">
<?php while ( $my_posts->have_posts() ) : $my_posts->the_post() ?>
<?php
$dateformatstring = 'F';
$unixtimestamp = strtotime(get_field('start_date'));
$year1 = date_i18n($dateformatstring, $unixtimestamp);
$year_check2 = $GLOBALS['year_checkbarcelonafunctions'];
// If your year hasn't been echoed earlier in the loop, echo it now
if (($year1 !== $year_check1) && ($year1 !== $year_check2)){
echo "<h2 class='year-act text-center'>" . $year1 . "</h2>";
}
// Now that your year has been printed, assign it to the $year_check variable
$test = 'November';
$GLOBALS['year_checkbarcelona1'] = $test;
$year_check1 = $year1;
?>
Code in functions.php:
function load_posts_by_ajax_callback2() {
check_ajax_referer('load_more_posts2', 'security2');
$paged = $_POST['page'];
$today = current_time('Y-m-d');
$args = array (
'meta_query' => array(
'relation' => 'AND',
array(
'category' => 'actividades',
'key' => 'start_date',
'value' => $today,
'compare' => '<',
'type' => 'DATE',
),
array(
'key' => 'region',
'value' => 'Barcelona',
'compare' => '='
),
),
'meta_key' => 'start_date',
'orderby' => 'meta_value',
'order' => 'DSC',
'posts_per_page' => 3,
'paged' => $paged,
);
$query = new WP_Query( $args ); ?>
<?php if ( $query->have_posts() ) : ?>
<?php while ( $query->have_posts() ) : $query->the_post();?>
<?php
$dateformatstring = 'F';
$unixtimestamp = strtotime(get_field('start_date'));
$year = date_i18n($dateformatstring, $unixtimestamp);
//Example another global
//$paged = $_POST['page'];
$year_check1 = $GLOBALS['year_checkbarcelona1'];
// If your year hasn't been echoed earlier in the loop, echo it now
if (($year !== $year_check) && ($year !== $year_check1)){
echo "<h2 class='year-act text-center'>" . $year . "</h2>";
}
// Now that your year has been printed, assign it to the $year_check variable
$GLOBALS['year_checkbarcelonafunctions'] = $year;
$year_check = $year;
?>
So in other words, the global values should avoid duplicating the $year tag that groups the activities/events when doing ajax loading.
Edit: I'm open to other solutions that don't rely on globals.
Edit3: I'm using this code (that is not working) inside the loop of the events template:
global $mytest2;
$mytest2 = 'November';
and in the functions.php inside the function load_posts_by_ajax_callback2, I have tried with
ob_start();
global $mytest2;
echo $mytest2;
$myStr = ob_get_contents();
ob_end_clean();
if (($year !== $year_check) && ($year !== $myStr)){
echo "<h2 class='year-act text-center'>" . $year . "</h2>";
}

Gravity Forms & Advanced Custom Fields

I've successfully created the dropdown menu to auto populate the appropriate information from an Advanced Custom Field I created called 'date' on site http://albertson.staging.wpengine.com/seminars/.
Followed along with the instructions here:
http://www.gravityhelp.com/documentation/page/Dynamically_Populating_Drop_Down_Fields
The only issue I'm having is how to display the date in a "pretty" format. You can see that the date is all numbers (20140129) instead of 01/28/2014
To display the date appropriately in the seminar sections above (border red) I use:
<?php if( get_field('date')): ?>
<?php
$date = get_field('date');
// $date = 19881123 (23/11/1988)
// extract Y,M,D
$y = substr($date, 0, 4);
$m = substr($date, 4, 2);
$d = substr($date, 6, 2);
// create UNIX
$time = strtotime("{$d}-{$m}-{$y}");
// format date (November 11th 1988)
echo date('M d', $time);
?>
How do I pass this same information within the Gravity Forms Function I created to get the date to display nicely? Below is my function for Gravity Forms so far.
add_filter('gform_pre_render_4', 'populate_dates');
function populate_dates($form){
foreach($form['fields'] as &$field){
if($field['type'] != 'select' || strpos($field['cssClass'], 'populate-dates') === false)
continue;
// you can add additional parameters here to alter the posts that are retreieved
// more info: http://codex.wordpress.org/Template_Tags/get_posts
$currentdate = date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")));
$events = get_posts(array(
'post_type' => 'seminars',
'orderby' => 'date',
'order' => 'ASC',
'meta_query'=> array(
array(
'key' => 'date',
'compare' => '>=',
'value' => $currentdate,
'type' => 'DATE',
)),
'meta_key' => 'date',
));
// update 'Select a Post' to whatever you'd like the instructive option to be
$choices = array(array('text' => 'Select a Date', 'value' => ' '));
foreach($events as $post){
$choices[] = array('text' => $post->date, 'value' => $post->date);
}
$field['choices'] = $choices;
}
return $form;
}
Sounds like you're looking for PHP's date function. We convert the date string to a timestamp via strtotime() and then use date() to format the date as you wish.
$formatted_date = date( 'm/d/Y', strtotime( $post->date ) );
In your code example:
foreach( $events as $post ){
$formatted_date = date( 'm/d/Y', strtotime( $post->date ) );
$choices[] = array('text' => $formatted_date, 'value' => $post->date );
}

Function printing but not working into an array

We are having troubles trying to insert multiple values generated from a function into an array.
When we print the function using a string and we copy the results manually it works but when we try to make it work using the string into an array it doesn't.
<?php
function dateRange( $first, $last, $step = '+1 day', $format = 'm/d/Y' ) {
$current = strtotime( $first );
$last = strtotime( $last );
while( $current <= $last ) {
$dates .= "'" . date( $format, $current) . "', ";
$current = strtotime( $step, $current );
}
return $dates;
}
$all_dates = dateRange( '01/20/1999', '01/23/1999');
echo $all_dates; /* PRINTS ALL DATES BETWEEN TWO DATES: '01/20/1999', '01/21/1999', '01/22/1999', '01/23/1999', */
query_posts( array(
'post_type' => 'bbdd',
'meta_query' => array(
$location,
array(
'key' => 'date',
'value' => array($all_dates), /* DOESN'T WORK. INSTEAD, IF WE COPY THE RESULT OF "echo $all_dates;" MANUALLY, IT DOES WORK */
),
)
) );
?>
You're returning a string, not an array, in the function.
function dateRange( $first, $last, $step = '+1 day', $format = 'm/d/Y' ) {
$current = strtotime( $first );
$last = strtotime( $last );
while( $current <= $last ) {
$dates[] = date($format, $current);
$current = strtotime($step, $current );
}
return $dates;
}
That will return an array.
Then, in your mysql query:
'value' => $all_dates
Why not put it in an array in the first place:
<?php
function dateRange( $first, $last, $step = '+1 day', $format = 'm/d/Y' ) {
$dates = array();
$current = strtotime( $first );
$last = strtotime( $last );
while( $current <= $last ) {
$dates[] = date($format, $current);
$current = strtotime( $step, $current );
}
return $dates;
}
?>

Categories