In Wordpress, can I use WP_Query with timestamp? - php

I have code like this,
$date_arg = array(
'after' => array(
'year' => $num_days_ago['year'],
'month' => $num_days_ago['mon'],
'day' => $num_days_ago['mday'],
),
'inclusive' => false,
);
$query = new WP_Query( array ( 'date_query' => $date_arg, 'post_type' => $post_type ...
This is working fine but I have to specify a exact date. Is it possible to use "timestamp" to make the query.
For example, I want to query posts that is within 24 hours. I can get the timestamp by
$ts = time() - DAY_IN_SECONDS
It is possible to get the posts that is created after $ts?

You could try constructing a date using the date() and strtotime() functions.
$date_query = array(
'after' => date('Y-m-d H:i:s', strtotime('-24 hours'))
);
I'd also recommend taking a look at this handy website - http://www.viper007bond.com/tag/wp_date_query/

IMHO better like so :
function filter_where($where = '') {
$where .= " AND post_date > '" . date('Y-m-d H:i:s', strtotime('-24 hours')) . "'";
return $where;
}
add_filter('posts_where', 'filter_where');
and more general :
// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
// posts in the last x days
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";// here 30
return $where;
}
add_filter( 'posts_where', 'filter_where' ); // add the filter before setting object or before loop
$query = new WP_Query( $query_string );
remove_filter( 'posts_where', 'filter_where' ); // .. and do not forget to remove it

Or you could try something like this
SELECT post_title, IF (post_date_gmt < (DATE_SUB(CURDATE(), INTERVAL 24 HOUR)), 'false', 'true') AS A FROM wp_posts
WHERE post_type = "post" AND post_status = "publish"
http://www.w3schools.com/sql/func_date_sub.asp

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

display most commented posts last month wordpress

I am trying to display most commented posts of certain category last month.
This is my code for now, I cant figure out what is wrong here, any ideas?
<?php
function filter_where( $where = '' ) {
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
return $where;
}
add_filter( 'posts_where', 'filter_where' );
$the_query = new WP_Query(array( 'posts_per_page' => 3, 'cat' => 2, 'orderby' => 'comment_count date', 'order'=> 'DESC' ));
remove_filter( 'posts_where', 'filter_where' );
?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
echo get_the_title();
// and rest of content
endwhile;
wp_reset_postdata(); ?>
edit: p.s. btw I am using Vkontakte Api plugin for my comments. May be the problem is here, because this code actually works fine on other site. But, get_comments_number() shows the correct number, why then orderby => comment_count doesnt work?
You have to use date_query, for this.
$args = [
'posts_per_page' => 3,
'post_type' => 'post',
'date_query' => [
[
'year' => date('Y', strtotime(date('Y-m-d') . " -1 month")),
'month' => date('m', strtotime(date('Y-m-d') . " -1 month"))
]
],
'orderby' => 'comment_count',
'order' => 'DESC'
];
$posts = new WP_Query($args);
//$posts = get_posts($args);
//print_r($posts);
The MySQL query will be for getting the popular post of last month will be: (assuming NOW() = 13 Feb 2017)
SELECT
posts.ID,
posts.post_title,
posts.post_date
FROM
wp_posts AS posts
WHERE
YEAR (posts.post_date) = 2017
AND MONTH (posts.post_date) = 1
AND posts.post_type = 'post'
AND posts.post_status = 'publish'
ORDER BY
posts.comment_count DESC
LIMIT 0, 3;
Hope this helps!

Get All WP Posts older than 15 minutes

I would like to filter the WP_Query to retrive all woocommerce order (post_type = shop_order) with particular status that are older than 15 minutes.
I.e. All posts that have been last modified on or before (now - 15 minutes ) // Hope I'm clear.
Below What I've tried
function filter_where($where = '') {
//posts in the last 15 minutes
$where .= " AND post_modified > '" . date('Y-m-d', strtotime('INTERVAL 15 MINUTE')) . "'";
return $where;
}
add_filter('posts_where', 'filter_where');
$args = array(
'post_type' => 'shop_order',
'post_status' => 'publish',
'posts_per_page' => 10,
'tax_query' => array(
array(
'taxonomy' => 'shop_order_status',
'field' => 'slug',
'terms' => array('completed')
)
)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$order_id = $loop->post->ID;
$order = new WC_Order($order_id);
print_r("<pre>");
print_r($order);
print_r("</pre>");
endwhile;
However that returns all record, Seems like have to modify the $where query, how can i achieve that ?
Do you need to filter the posts_where? Can't you just use date query parameters? In your case, specifically before.
$args = array(
'date_query' => array(
array(
'before' => '15 minutes ago'
'inclusive' => true,
),
),
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
I can't test this right now, so can't verify if it would work. If you are modifying an archive then you should definitely adjust the query via pre_get_posts in lieu of creating new query.
try this change date('Y-m-d', strtotime('INTERVAL 15 MINUTE')) to date('Y-m-d H:i:s', strtotime('-15 minutes'))
function filter_where($where = ''){
//posts in the last 15 minutes
$where .= " AND post_modified > '" . date('Y-m-d H:i:s', strtotime('-15 minutes')) . "'";
return $where;
}
add_filter('posts_where', 'filter_where');

Get orders by date and status woocommerce

I need get a list of orders in woocommerce passing start date, final date and status.
I tryed use some techniques like described by Mike Jolley, and I mixed with this. But I have not had success. This return all orders. I´m using the woocommerce version 2.2.10.
Thanks for help.
My code:
public function get_orders(){
global $json_api;
$initial_date = $json_api->query->para1;
$final_date = $json_api->query->para2;
$order_id = $json_api->query->para3;
$status_order = $json_api->query->para4;
define('GET_ORDERS_FILTER_DATE_FROM', $initial_date );
define('GET_ORDERS_FILTER_DATE_TO', $final_date );
add_filter('posts_where', array( __CLASS__, 'get_orders_where_dates_between') );
$orders = get_posts( array(
'post_type' => 'shop_order',
'orderby' => 'post_date',
'order' => 'DESC',
'post_status' => array_keys( $status_order )
) );
remove_filter('posts_where', 'order_page_get_orders_where_dates_between');
return $orders;
}
function get_orders_where_dates_between( $where ){
global $wpdb;
if( ! defined('GET_ORDERS_FILTER_DATE_FROM') || ! defined('PARCELWARE_GET_ORDERS_FILTER_DATE_TO') )
return $where;
$where .= $wpdb->prepare(" AND post_date >= '%s' ", GET_ORDERS_FILTER_DATE_FROM);
$where .= $wpdb->prepare(" AND post_date <= '%s' ", GET_ORDERS_FILTER_DATE_TO);
return $where;
}
You can use wc_get_orders
$initial_date = yyyy-mm-dd;
$final_date = yyyy-mm-dd;
$orders = wc_get_orders(array(
'limit'=>-1,
'type'=> 'shop_order',
'status'=> array( 'wc-completed','wc-refunded' ),
'date_created'=> $initial_date .'...'. $final_date
)
);
How about using custom wpdb query like this?
global $wpdb;
$date_from = '2015-11-20';
$date_to = '2015-12-20';
$post_status = implode("','", array('wc-processing', 'wc-completed') );
$result = $wpdb->get_results( "SELECT * FROM $wpdb->posts
WHERE post_type = 'shop_order'
AND post_status IN ('{$post_status}')
AND post_date BETWEEN '{$date_from} 00:00:00' AND '{$date_to} 23:59:59'
");
echo "<pre>";
print_r($result);
If you want to use timestamps (date AND time):
$timestamp_start = '2022-04-07 20:00:00.000'; // example
$timestamp_end = '2022-04-21 20:00:01.000'; // example
'date_created' => strtotime($timestamp_start ) .'...'. strtotime($timestamp_end)

Show latest post from each author if post is not older than a month

I have a list of the authors (Wordpress) on the site that appears on every page so the list exists outside of the loop.
I managed to show every authors' image with their names but I would like to get their latest post title that links to the post. The post title should only show when the post is not older than a month.
Any help would be appreciated.
Thanks
<?php
global $wpdb;
$query = "SELECT ID, user_nicename from $wpdb->users WHERE ID != '1' ORDER BY 'ASC' LIMIT 20";
$author_ids = $wpdb->get_results($query);
foreach($author_ids as $author) :
// Get user data
$curauth = get_userdata($author->ID);
// Get link to author page
$user_link = get_author_posts_url($curauth->ID);
$post_link = get_permalink($curauth->ID);
// Set default avatar (values = default, wavatar, identicon, monsterid)
$main_profile = get_the_author_meta('mainProfile', $curauth->ID);
$hover_profile = get_the_author_meta('hoverProfile', $curauth->ID);
$award_profile = get_the_author_meta('awardProfile', $curauth->ID);
?>
You can use WP_Query to create a new loop for you instead. It accepts a cool date_query argument since version 3.7. Untested, but should work.
EDITED:
$args = array(
'showposts' => 1,
'orderby' => 'date',
'date_query' => array(
array(
'after' => array(
'year' => date( "Y" ),
'month' => date( "m", strtotime( "-1 Months" ) ),
'day' => date( "t", strtotime( "-1 Months" ) ),
),
'inclusive' => true,
)
) );
$query = new WP_Query( $args );
Then you can just run a regular loop
// run the loop with $query
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
echo 'Latest post: ' . get_the_title();
}
} else {
// no posts
}

Categories