Function printing but not working into an array - php

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;
}
?>

Related

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

Sorting array of days from a random order with a specific start date

I have this kind of array of days in a random order (number of days can be 1 until 5) :
$jour_planning[] = "sunday";
$jour_planning[] = "wednesday";
$jour_planning[] = "monday";
I would like to sort them, starting of "today".
I have this code working but only for 7 days in the array, how to adapt it ?
function sort_week_days( $t1, $t2 ) {
$weekdays = array( 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' );
foreach ( $weekdays as $key => $value ) {
$weekdays[ $key ] = date( 'w', strtotime( $value ) );
}
$t1_time = date( 'w', strtotime( strtolower( $t1 ) ) );
$t2_time = date( 'w', strtotime( strtolower( $t2 ) ) );
return array_search( $t1_time, $weekdays ) - array_search( $t2_time, $weekdays );
}
usort($jour_planning, "sort_week_days");
$today_day = date('w', '-1day');
for ($i=0; $i <= $today_day ; $i++) {
array_push($jour_planning, array_shift($jour_planning));
}

Year and Month in Wordpress Archive List

I'd like to list all years from which there are public Wordpress posts, and in a sub-menu below, the months from those years. Example:
2016
August
March
2015
June
May
February
I have a working version of this inside a loop, but it requires me to manually add a new list every year. Is there any way to adjust it, so that it includes the new year automatically?
<h1>2016</h1>
<ul>
<?php
$string = wp_get_archives('type=monthly&year=2016&echo=0');
$pattern = ' ((19|20)\d{2}(</a>))';
echo preg_replace($pattern, '\\3', $string); '<li></li>';?>
</ul></a>
<h1>2015</h1>
<?php
$string = wp_get_archives('type=monthly&year=2015&echo=0');
$pattern = ' ((19|20)\d{2}(</a>))';
echo preg_replace($pattern, '\\3', $string); '<li></li>';?>
</ul></a>
Ok, found a very helpful post on stack exchange: here
Basically, add this to functions.php:
//List archives by year, then month
function wp_custom_archive($args = '') {
global $wpdb, $wp_locale;
$defaults = array(
'limit' => '',
'format' => 'html', 'before' => '',
'after' => '', 'show_post_count' => false,
'echo' => 1
);
$r = wp_parse_args( $args, $defaults );
extract( $r, EXTR_SKIP );
if ( '' != $limit ) {
$limit = absint($limit);
$limit = ' LIMIT '.$limit;
}
// over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
$archive_date_format_over_ride = 0;
// options for daily archive (only if you over-ride the general date format)
$archive_day_date_format = 'Y/m/d';
// options for weekly archive (only if you over-ride the general date format)
$archive_week_start_date_format = 'Y/m/d';
$archive_week_end_date_format = 'Y/m/d';
if ( !$archive_date_format_over_ride ) {
$archive_day_date_format = get_option('date_format');
$archive_week_start_date_format = get_option('date_format');
$archive_week_end_date_format = get_option('date_format');
}
//filters
$where = apply_filters('customarchives_where', "WHERE post_type = 'post' AND post_status = 'publish'", $r );
$join = apply_filters('customarchives_join', "", $r);
$output = '<ul>';
$query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC $limit";
$key = md5($query);
$cache = wp_cache_get( 'wp_custom_archive' , 'general');
if ( !isset( $cache[ $key ] ) ) {
$arcresults = $wpdb->get_results($query);
$cache[ $key ] = $arcresults;
wp_cache_set( 'wp_custom_archive', $cache, 'general' );
} else {
$arcresults = $cache[ $key ];
}
if ( $arcresults ) {
$afterafter = $after;
foreach ( (array) $arcresults as $arcresult ) {
$url = get_month_link( $arcresult->year, $arcresult->month );
$year_url = get_year_link($arcresult->year);
/* translators: 1: month name, 2: 4-digit year */
$text = sprintf(__('%s'), $wp_locale->get_month($arcresult->month));
$year_text = sprintf('%d', $arcresult->year);
if ( $show_post_count )
$after = ' ('.$arcresult->posts.')' . $afterafter;
$year_output = get_archives_link($year_url, $year_text, $format, $before, $after);
$output .= ( $arcresult->year != $temp_year ) ? $year_output : '';
$output .= get_archives_link($url, $text, $format, $before, $after);
$temp_year = $arcresult->year;
}
}
$output .= '</ul>';
if ( $echo )
echo $output;
else
return $output;
}
And then call this function on the page:
<?php wp_custom_archive(); ?>
It will return a list exactly as needed, by year then month, with links to each!
<select name="archive-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Month' ) ); ?></option>
<?php wp_get_archives( array( 'type' => 'monthly', 'format' => 'option', 'show_post_count' => 1 ) ); ?>
</select>
I would do it this way.
It's a bit shorter and easier to understand, and it relies on WP core functions, which is usually the preferable way to handle the data in WP. Also, it doesn't need expensive regex functions.
1. Add "in_year" option to the wp_get_archives() function
<?php
add_filter( 'getarchives_where', 'archives_in_specific_year', 10, 2 );
function archives_in_specific_year( $sql_where, $parsed_args ) {
if ( ! empty( $parsed_args['in_year'] ) ) {
$year = absint( $parsed_args['in_year'] );
$sql_where .= " AND YEAR(post_date) = $year";
}
return $sql_where;
}
?>
2. For each year, render that year and its months
<?php
$args = [
'type' => 'yearly',
'echo' => false,
];
$years = wp_get_archives( $args );
$years_array = explode( "\t", trim( wp_strip_all_tags( $years ) ) );
foreach ( $years_array as $current_year ) {
$current_year = intval( $current_year );
$monthly_args = [
'type' => 'monthly',
'format' => 'custom',
'echo' => false,
'before' => '<span>',
'after' => '</span>',
'in_year' => $current_year,
];
$months = str_replace( ' ' . $current_year, '', wp_get_archives( $monthly_args ) );
$yearly_args = [
'type' => 'yearly',
'after' => '<div>' . $months . '</div>',
'in_year' => $current_year,
];
wp_get_archives( $yearly_args );
}
?>
here's a simple mysql query, solved a similiar problem.
$query = 'SELECT DISTINCT MONTH(`post_date`) AS `month`, YEAR(`post_date`) AS `year` FROM `wp_posts` ORDER BY `post_date` ASC';
$results = $wpdb->get_results($query);

Warning: date() expects parameter 2 to be long,

Getting the followoing error:
Warning: date() expects parameter 2 to be long, string given in
/home/users/2/catfood.jp-cybercat/web/academy/wp-includes/functions.php
on line 112
Which points to the line:
$datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
What changes are required to the above line to resolve this?
Here is the whole codes
function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
global $wp_locale;
$i = $unixtimestamp;
if ( false === $i ) {
if ( ! $gmt )
$i = current_time( 'timestamp' );
else
$i = time();
// we should not let date() interfere with our
// specially computed timestamp
$gmt = true;
}
/*
* Store original value for language with untypical grammars.
* See https://core.trac.wordpress.org/ticket/9396
*/
$req_format = $dateformatstring;
$datefunc = $gmt? 'gmdate' : 'date';
if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
$datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
$datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
$dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) );
$dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
$datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) );
$datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) );
$dateformatstring = ' '.$dateformatstring;
$dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
$dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
$dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
$dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
$dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
$dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
$dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
}
$timezone_formats = array( 'P', 'I', 'O', 'T', 'Z', 'e' );
$timezone_formats_re = implode( '|', $timezone_formats );
if ( preg_match( "/$timezone_formats_re/", $dateformatstring ) ) {
$timezone_string = get_option( 'timezone_string' );
if ( $timezone_string ) {
$timezone_object = timezone_open( $timezone_string );
$date_object = date_create( null, $timezone_object );
foreach( $timezone_formats as $timezone_format ) {
if ( false !== strpos( $dateformatstring, $timezone_format ) ) {
$formatted = date_format( $date_object, $timezone_format );
$dateformatstring = ' '.$dateformatstring;
$dateformatstring = preg_replace( "/([^\\\])$timezone_format/", "\\1" . backslashit( $formatted ), $dateformatstring );
$dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
}
}
}
}
$j = #$datefunc( $dateformatstring, $i );
/**
* Filter the date formatted based on the locale.
*
* #since 2.8.0
*
* #param string $j Formatted date string.
* #param string $req_format Format to display the date.
* #param int $i Unix timestamp.
* #param bool $gmt Whether to convert to GMT for time. Default false.
*/
$j = apply_filters( 'date_i18n', $j, $req_format, $i, $gmt );
return $j;
}
$datefunc is an alias obviously to php's date method. If that's the case, you are trying to get the month from passing a single integer 1-12. When you can't do that, you need to pass a timestamp to PHP's date method then depending on the attributes you pass as options will return you the following data. Then you are passing it to wordpress locale get_month method that returns the name of the month. You need to refactor your code, so that $i isn't a for loop variable. If you are just trying to get Jan - Dec just do
$i = 1;
$monthArray = [];
do {
// Just push the months to an array and pass it to the view
array_push($monthArray, $wp_locale->get_month($i);
$i++;
} while($i < 13);
Then do what you need to with it. If you are getting a record back from the DB, you need to access the appropriate value in the returned model. Otherwise you're passing an array object. If you are accessing a model you should do)
// Access the property that you intended to retrieve the month on.
$datemonth = $wp_locale->get_month( $datefunc( 'm', $i['published_at'] ) );
I added a plugin called "paid membership pro" and this plugin was written in English and I translated into Japanese. There were lots of codes like this:
<?php printf(__('課金 #%s ( %s )', 'pmpro'), $pmpro_invoice->code, date_i18n(get_option('date_format'), $pmpro_invoice->timestamp));?>
I tried to change these codes as follows:
timestamp), $pmpro_invoice->code );?>
I guess that's why it caused the problem. What do you think?
Now I downloaded the plugin again and there is no problem.
Thank you for helping me.

categories the posts month wise in wordpress?

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

Categories