Modify code to change timestamp timezone in sitemap - php

Below is the code from a plugin I use for sitemaps.
I would like to know if there's a way to "enforce" a different timezone on all date variable and functions in it.
If not, how do I modify the code to change the timestamp to reflect a different timezone? Say for example, to America/New_York timezone.
Please look for date to quickly get to the appropriate code blocks. Code on Pastebin.
<?php
/**
* #package XML_Sitemaps
*/
class WPSEO_Sitemaps {
.....
/**
* Build the root sitemap -- example.com/sitemap_index.xml -- which lists sub-sitemaps
* for other content types.
*
* #todo lastmod for sitemaps?
*/
function build_root_map() {
global $wpdb;
$options = get_wpseo_options();
$this->sitemap = '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
$base = $GLOBALS['wp_rewrite']->using_index_permalinks() ? 'index.php/' : '';
// reference post type specific sitemaps
foreach ( get_post_types( array( 'public' => true ) ) as $post_type ) {
if ( $post_type == 'attachment' )
continue;
if ( isset( $options['post_types-' . $post_type . '-not_in_sitemap'] ) && $options['post_types-' . $post_type . '-not_in_sitemap'] )
continue;
$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(ID) FROM $wpdb->posts WHERE post_type = %s AND post_status = 'publish' LIMIT 1", $post_type ) );
// don't include post types with no posts
if ( !$count )
continue;
$n = ( $count > 1000 ) ? (int) ceil( $count / 1000 ) : 1;
for ( $i = 0; $i < $n; $i++ ) {
$count = ( $n > 1 ) ? $i + 1 : '';
if ( empty( $count ) || $count == $n ) {
$date = $this->get_last_modified( $post_type );
} else {
$date = $wpdb->get_var( $wpdb->prepare( "SELECT post_modified_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = %s ORDER BY post_modified_gmt ASC LIMIT 1 OFFSET %d", $post_type, $i * 1000 + 999 ) );
$date = date( 'c', strtotime( $date ) );
}
$this->sitemap .= '<sitemap>' . "\n";
$this->sitemap .= '<loc>' . home_url( $base . $post_type . '-sitemap' . $count . '.xml' ) . '</loc>' . "\n";
$this->sitemap .= '<lastmod>' . htmlspecialchars( $date ) . '</lastmod>' . "\n";
$this->sitemap .= '</sitemap>' . "\n";
}
}
// reference taxonomy specific sitemaps
foreach ( get_taxonomies( array( 'public' => true ) ) as $tax ) {
if ( in_array( $tax, array( 'link_category', 'nav_menu', 'post_format' ) ) )
continue;
if ( isset( $options['taxonomies-' . $tax . '-not_in_sitemap'] ) && $options['taxonomies-' . $tax . '-not_in_sitemap'] )
continue;
// don't include taxonomies with no terms
if ( !$wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->term_taxonomy WHERE taxonomy = %s AND count != 0 LIMIT 1", $tax ) ) )
continue;
// Retrieve the post_types that are registered to this taxonomy and then retrieve last modified date for all of those combined.
$taxobj = get_taxonomy( $tax );
$date = $this->get_last_modified( $taxobj->object_type );
$this->sitemap .= '<sitemap>' . "\n";
$this->sitemap .= '<loc>' . home_url( $base . $tax . '-sitemap.xml' ) . '</loc>' . "\n";
$this->sitemap .= '<lastmod>' . htmlspecialchars( $date ) . '</lastmod>' . "\n";
$this->sitemap .= '</sitemap>' . "\n";
}
// allow other plugins to add their sitemaps to the index
$this->sitemap .= apply_filters( 'wpseo_sitemap_index', '' );
$this->sitemap .= '</sitemapindex>';
}
/**
* Build a sub-sitemap for a specific post type -- example.com/post_type-sitemap.xml
*
* #param string $post_type Registered post type's slug
*/
function build_post_type_map( $post_type ) {
$options = get_wpseo_options();
............
// We grab post_date, post_name, post_author and post_status too so we can throw these objects into get_permalink, which saves a get_post call for each permalink.
while ( $total > $offset ) {
$join_filter = apply_filters( 'wpseo_posts_join', '', $post_type );
$where_filter = apply_filters( 'wpseo_posts_where', '', $post_type );
// Optimized query per this thread: http://wordpress.org/support/topic/plugin-wordpress-seo-by-yoast-performance-suggestion
// Also see http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/
$posts = $wpdb->get_results( "SELECT l.ID, post_content, post_name, post_author, post_parent, post_modified_gmt, post_date, post_date_gmt
FROM (
SELECT ID FROM $wpdb->posts {$join_filter}
WHERE post_status = 'publish'
AND post_password = ''
AND post_type = '$post_type'
{$where_filter}
ORDER BY post_modified ASC
LIMIT $steps OFFSET $offset ) o
JOIN $wpdb->posts l
ON l.ID = o.ID
ORDER BY l.ID" );
/* $posts = $wpdb->get_results("SELECT ID, post_content, post_name, post_author, post_parent, post_modified_gmt, post_date, post_date_gmt
FROM $wpdb->posts {$join_filter}
WHERE post_status = 'publish'
AND post_password = ''
AND post_type = '$post_type'
{$where_filter}
ORDER BY post_modified ASC
LIMIT $steps OFFSET $offset"); */
$offset = $offset + $steps;
foreach ( $posts as $p ) {
$p->post_type = $post_type;
$p->post_status = 'publish';
$p->filter = 'sample';
if ( wpseo_get_value( 'meta-robots-noindex', $p->ID ) && wpseo_get_value( 'sitemap-include', $p->ID ) != 'always' )
continue;
if ( wpseo_get_value( 'sitemap-include', $p->ID ) == 'never' )
continue;
if ( wpseo_get_value( 'redirect', $p->ID ) && strlen( wpseo_get_value( 'redirect', $p->ID ) ) > 0 )
continue;
$url = array();
$url['mod'] = ( isset( $p->post_modified_gmt ) && $p->post_modified_gmt != '0000-00-00 00:00:00' ) ? $p->post_modified_gmt : $p->post_date_gmt;
$url['chf'] = 'weekly';
$url['loc'] = get_permalink( $p );
.............
}
/**
* Build a sub-sitemap for a specific taxonomy -- example.com/tax-sitemap.xml
*
* #param string $taxonomy Registered taxonomy's slug
*/
function build_tax_map( $taxonomy ) {
$options = get_wpseo_options();
..........
// Grab last modified date
$sql = "SELECT MAX(p.post_date) AS lastmod
FROM $wpdb->posts AS p
INNER JOIN $wpdb->term_relationships AS term_rel
ON term_rel.object_id = p.ID
INNER JOIN $wpdb->term_taxonomy AS term_tax
ON term_tax.term_taxonomy_id = term_rel.term_taxonomy_id
AND term_tax.taxonomy = '$c->taxonomy'
AND term_tax.term_id = $c->term_id
WHERE p.post_status = 'publish'
AND p.post_password = ''";
$url['mod'] = $wpdb->get_var( $sql );
$url['chf'] = 'weekly';
$output .= $this->sitemap_url( $url );
}
}
/**
* Build the <url> tag for a given URL.
*
* #param array $url Array of parts that make up this entry
* #return string
*/
function sitemap_url( $url ) {
if ( isset( $url['mod'] ) )
$date = mysql2date( "Y-m-d\TH:i:s+00:00", $url['mod'] );
else
$date = date( 'c' );
$output = "\t<url>\n";
$output .= "\t\t<loc>" . $url['loc'] . "</loc>\n";
$output .= "\t\t<lastmod>" . $date . "</lastmod>\n";
$output .= "\t\t<changefreq>" . $url['chf'] . "</changefreq>\n";
$output .= "\t\t<priority>" . str_replace( ',', '.', $url['pri'] ) . "</priority>\n";
if ( isset( $url['images'] ) && count( $url['images'] ) > 0 ) {
foreach ( $url['images'] as $img ) {
$output .= "\t\t<image:image>\n";
$output .= "\t\t\t<image:loc>" . esc_html( $img['src'] ) . "</image:loc>\n";
if ( isset( $img['title'] ) )
$output .= "\t\t\t<image:title>" . _wp_specialchars( html_entity_decode( $img['title'], ENT_QUOTES, get_bloginfo('charset') ) ) . "</image:title>\n";
if ( isset( $img['alt'] ) )
$output .= "\t\t\t<image:caption>" . _wp_specialchars( html_entity_decode( $img['alt'], ENT_QUOTES, get_bloginfo('charset') ) ) . "</image:caption>\n";
$output .= "\t\t</image:image>\n";
}
}
$output .= "\t</url>\n";
return $output;
}
/**
* Get the modification date for the last modified post in the post type:
*
* #param array $post_types Post types to get the last modification date for
* #return string
*/
function get_last_modified( $post_types ) {
global $wpdb;
if ( !is_array( $post_types ) )
$post_types = array( $post_types );
$result = 0;
foreach ( $post_types as $post_type ) {
$key = 'lastpostmodified:gmt:' . $post_type;
$date = wp_cache_get( $key, 'timeinfo' );
if ( !$date ) {
$date = $wpdb->get_var( $wpdb->prepare( "SELECT post_modified_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = %s ORDER BY post_modified_gmt DESC LIMIT 1", $post_type ) );
if ( $date )
wp_cache_set( $key, $date, 'timeinfo' );
}
if ( strtotime( $date ) > $result )
$result = strtotime( $date );
}
// Transform to W3C Date format.
$result = date( 'c', $result );
return $result;
}
}
global $wpseo_sitemaps;
$wpseo_sitemaps = new WPSEO_Sitemaps();

I believe you're looking for the date_default_timezone_set() function, which will force all date functions, including date(), to use the specified time zone.
date_default_timezone_set( 'America/New_York');
For your specific case to only have changes apply to the plugin, you should save the current timezone with date_default_timezone_get(), then set your own timezone, and revert it when you're done. So, you could do something like this:
class WPSEO_Sitemaps {
private $old_timezone = '';
private $new_timezone = 'America/New_York';
function setTimezone() {
$this->old_timezone = date_default_timezone_get();
date_default_timezone_set( $this->new_timezone);
}
function revertTimezone() {
date_default_timezone_set( $this->old_timezone);
}
function foo() {
$this->setTimezone();
date();
$tihs->revertTimezone();
}
}

Related

How to move part of text to another line in PHP

Here is the code I am using:
// Display the product variation price inside the variations dropdown. add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );
function display_price_in_variation_option_name( $term ) {
global $wpdb, $product;
if ( empty( $term ) ) {
return $term;
}
if ( empty( $product->id ) ) {
return $term;
}
$result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE name = '$term'" );
$term_slug = ( ! empty( $result ) ) ? $result[0] : $term;
$query = "
SELECT postmeta.post_id AS product_id
FROM {$wpdb->prefix}postmeta AS postmeta
LEFT JOIN {$wpdb->prefix}posts AS products ON ( products.ID = postmeta.post_id )
WHERE postmeta.meta_key LIKE 'attribute_%'
AND postmeta.meta_value = '$term_slug'
AND products.post_parent = $product->id";
$variation_id = $wpdb->get_col( $query );
$parent = wp_get_post_parent_id( $variation_id[0] );
if ( $parent > 0 ) {
$_product = new WC_Product_Variation( $variation_id[0] );
return '' . $term . '' . ' - (' . wp_kses( woocommerce_price( $_product->get_price() ), array() ) . ' )';
}
return $term;
}
And this is how it's in front: Screenshot
Could anybody tell me how can I move everything starting from "-" to the next line?
It has to look this way:
38 Euro
20 0000
You can change the return part to this:
if ( $parent > 0 ) {
$_product = new WC_Product_Variation( $variation_id[0] );
return '' . $term . '' . ' <br/> ' . wp_kses( woocommerce_price( $_product->get_price(), array() ) . ' )';
}
return $term;
Also, edit your code in the part that returns the HTML to unescape the $name variable:
return sprintf( '<li class="swatch swatch-label swatch-%s %s %s %s %s" title="%s" data-value="%s" data-tooltip_type="%s" data-tooltip_value="%s"><span class="swatch-inner swatch-label-inner">%s</span></li>', esc_attr( $slug ), esc_attr( $selected ), esc_attr( $style ), esc_attr( $flex_mode_class ), esc_attr( $tooltip_class ), $name, esc_attr( $slug ), esc_attr( $tooltip ), esc_attr( $tooltip_value ), $name );
In addition, to not break your grid, you will need to add this css to your stylesheet, or in the theme setting, in Custom CSS:
.xt_woovs-single-product .xt_woovs-swatches .swatch.swatch-label {
height: auto !important;
text-align: left !important;
}

add hook in product search query

I'm developing a plugin for my shopping site. The plugin works like this. Color variations of the same product are on different product pages. The products are connected together as shown in the photo below.
and on the product page as small photos, it is shown as color variants of the product.
It works flawlessly so far.
but I am using multi-vendor plugin on my website.
. I want it to search only the products belonging to the author, the user, that is the store, while selecting the product.
for this, is it possible to add a filter to the query made in the ajax request and rewrite the query?
add_filter('woocommerce_product_pre_search_products', 'woocommerce_product_pre_search_products', 10, 6);
function woocommerce_product_pre_search_products( $custom_query=false, $term, $type, $include_variations, $all_statuses, $limit) {
global $wpdb;
$post_types = $include_variations ? array( 'product', 'product_variation' ) : array( 'product' );
$join_query = '';
$type_where = '';
$status_where = '';
$limit_query = '';
// When searching variations we should include the parent's meta table for use in searches.
if ( $include_variations ) {
$join_query = " LEFT JOIN {$wpdb->wc_product_meta_lookup} parent_wc_product_meta_lookup
ON posts.post_type = 'product_variation' AND parent_wc_product_meta_lookup.product_id = posts.post_parent ";
}
/**
* Hook woocommerce_search_products_post_statuses.
*
* #since 3.7.0
* #param array $post_statuses List of post statuses.
*/
$post_statuses = apply_filters(
'woocommerce_search_products_post_statuses',
current_user_can( 'edit_private_products' ) ? array( 'private', 'publish' ) : array( 'publish' )
);
// See if search term contains OR keywords.
if ( stristr( $term, ' or ' ) ) {
$term_groups = preg_split( '/\s+or\s+/i', $term );
} else {
$term_groups = array( $term );
}
$search_where = '';
$search_queries = array();
foreach ( $term_groups as $term_group ) {
$search_terms = array( $term_group );
$term_group_query = '';
$searchand = '';
foreach ( $search_terms as $search_term ) {
$like = '%' . $wpdb->esc_like( $search_term ) . '%';
// Variations should also search the parent's meta table for fallback fields.
if ( $include_variations ) {
$variation_query = $wpdb->prepare( " OR ( wc_product_meta_lookup.sku = '' AND parent_wc_product_meta_lookup.sku LIKE %s ) ", $like );
} else {
$variation_query = '';
}
$term_group_query .= $wpdb->prepare( " {$searchand} ( ( posts.post_title LIKE %s) OR ( posts.post_excerpt LIKE %s) OR ( posts.post_content LIKE %s ) OR ( wc_product_meta_lookup.sku LIKE %s ) $variation_query)", $like, $like, $like, $like ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$searchand = ' AND ';
}
if ( $term_group_query ) {
$search_queries[] = $term_group_query;
}
}
if ( ! empty( $search_queries ) ) {
$search_where = ' AND (' . implode( ') OR (', $search_queries ) . ') ';
}
if ( ! empty( $include ) && is_array( $include ) ) {
$search_where .= ' AND posts.ID IN(' . implode( ',', array_map( 'absint', $include ) ) . ') ';
}
if ( ! empty( $exclude ) && is_array( $exclude ) ) {
$search_where .= ' AND posts.ID NOT IN(' . implode( ',', array_map( 'absint', $exclude ) ) . ') ';
}
$search_where .= ' AND posts.post_author='. get_current_user_id();
if ( 'virtual' === $type ) {
$type_where = ' AND ( wc_product_meta_lookup.virtual = 1 ) ';
} elseif ( 'downloadable' === $type ) {
$type_where = ' AND ( wc_product_meta_lookup.downloadable = 1 ) ';
}
if ( ! $all_statuses ) {
$status_where = " AND posts.post_status IN ('" . implode( "','", $post_statuses ) . "') ";
}
if ( $limit ) {
$limit_query = $wpdb->prepare( ' LIMIT %d ', $limit );
}
// phpcs:ignore WordPress.VIP.DirectDatabaseQuery.DirectQuery
$search_results = $wpdb->get_results(
// phpcs:disable
"SELECT DISTINCT posts.ID as product_id, posts.post_parent as parent_id FROM {$wpdb->posts} posts
LEFT JOIN {$wpdb->wc_product_meta_lookup} wc_product_meta_lookup ON posts.ID = wc_product_meta_lookup.product_id
$join_query
WHERE posts.post_type IN ('" . implode( "','", $post_types ) . "')
$search_where
$status_where
$type_where
ORDER BY posts.post_parent ASC, posts.post_title ASC
$limit_query
"
// phpcs:enable
);
$product_ids = wp_parse_id_list( array_merge( wp_list_pluck( $search_results, 'product_id' ), wp_list_pluck( $search_results, 'parent_id' ) ) );
if ( is_numeric( $term ) ) {
$post_id = absint( $term );
$post_type = get_post_type( $post_id );
if ( 'product_variation' === $post_type && $include_variations ) {
$product_ids[] = $post_id;
} elseif ( 'product' === $post_type ) {
$product_ids[] = $post_id;
}
$product_ids[] = wp_get_post_parent_id( $post_id );
}
return wp_parse_id_list( $product_ids );
}

Make columns sortable in admin products list panel in Woocommerce

I added the column with the highest value of the offer. And then I would like to make it sortable. I've prepared this:
// asl this will add extra column in the product list
add_filter( 'manage_edit-product_columns', array($this,'show_product_offers_amounts'),15 );
add_action( 'manage_product_posts_custom_column', array($this,'show_product_offers_amount_max'), 10, 2 );
// asl show the column
function show_product_offers_amounts($columns){
$columns['orig_offer_amount'] = 'Amount';
return $columns;
}
// asl add the datas to column
function show_product_offers_amount_max( $column, $postid ) {
global $wpdb;
if ( $column == 'orig_offer_amount' ) {
$offers_max = $wpdb->get_var( " select max(meta_value)
from ".$wpdb->postmeta."
where meta_key='orig_offer_amount'
and meta_value!=''
and post_id in(
select p.post_id
from ".$wpdb->postmeta." as p
where p.meta_key='orig_offer_product_id' and
p.meta_value=".$postid.")"
);
if($offers_max > 0){
echo '<mark style="color: #3973aa;font-size: 13px;font-weight: 500;background: 0 0;line-height: 1;">'.$offers_max.'</mark>';
}
else{
echo '<span class="na">–</span>';
}
}
}
// asl register the column as sortable
function price_column_register_sortable( $columns ) {
$columns['orig_offer_amount'] = 'orig_offer_amount';
return $columns;
}
add_filter( 'manage_edit-product_sortable_columns', 'price_column_register_sortable' );
function price_column_orderby( $vars ) {
if ( isset( $vars['orderby'] ) && 'price' == $vars['orderby'] ) {
$offers_max = $wpdb->get_var( " select max(meta_value)
from ".$wpdb->postmeta."
where meta_key='orig_offer_amount'
and meta_value!=''
and post_id in(
select p.post_id
from ".$wpdb->postmeta." as p
where p.meta_key='orig_offer_product_id' and
p.meta_value=".$postid.")"
);
if($offers_max > 0){
$offers_max = $offers_max;
}
else{
$offers_max = 0;;
}
$vars = array_merge( $vars, array(
'meta_key' => 'orig_offer_amount',
'orderby' => $offers_max
) );
}
return $vars;
}
add_filter( 'request', 'price_column_orderby' );
This code makes that wordpress recognize the column as sortable. But it doesn't sort properly.
Any idea?
Using LoicTheAztec suggestion I prepared something like this:
add_action( 'save_post', 'new_postmeta_to_products' );
function new_postmeta_to_products($post_id){
$post_type = get_post_type($post_id);
if($post_type == 'products') {
global $wpdb;
$maxId = $wpdb->get_var( " select post_id
from ".$wpdb->postmeta."
where meta_key='orig_offer_amount'
and meta_value!=''
and post_id in(
select p.post_id
from ".$wpdb->postmeta." as p
where p.meta_key='orig_offer_product_id' and
p.meta_value=".$post_id.")
order by meta_value desc limit 1"
);
add_post_meta($post_id,'offer_max_id',$maxId);
}
}
But it doesn't work :( maybe because $post_id
Thanks to LoicTheAztec's hints I've prepared some snippet. First I've added new postmeta for product, when is created:
add_post_meta($post_id, 'offers_max_id', null);
add_post_meta($post_id, 'offers_max_value', null);
add_post_meta($post_id, 'offers_count', null);
Then, a few lines to set the new postmeta when an offer is created in www/wp-content/plugins/offers-for-woocommerce/public/class-offers-for-woocommerce.php in function new_offer_form_submit() :
global $post;
$_product = get_post_meta($parent_post_id, 'offer_product_id', true);
global $wpdb;
$offerMax = $wpdb->get_results( " select post_id, meta_value
from ".$wpdb->postmeta."
where meta_key='orig_offer_amount'
and meta_value!=''
and post_id in(
select p.post_id
from ".$wpdb->postmeta." as p
where p.meta_key='orig_offer_product_id' and
p.meta_value=".$_product.")
order by meta_value desc limit 1"
,ARRAY_N);
update_post_meta($_product, 'offers_max_id', $offerMax[0][0]);
update_post_meta($_product, 'offers_max_value', $offerMax[0][1]);
$offerCount = $wpdb->get_var( "select count(post_id)
from ".$wpdb->postmeta."
where meta_key='orig_offer_product_id' and
meta_value=".$_product
);
update_post_meta($_product, 'offers_count', $offerCount);
Then, we must add new columns for products' admin panel in function.php:
// asl show the column
function my_cpt_columns( $columns ) {
$columns["offermaxid"] = "OfferId";
$columns["offercount"] = "Offers";
$columns["offermaxvalue"] = "Amount";
$columns["dateofend"] = "EndTime";
return $columns;
}
add_filter('manage_edit-product_columns', 'my_cpt_columns');
// asl take a data to the column
function my_cpt_column( $colname, $cptid ) {
if ( $colname == 'offermaxid')
echo get_post_meta( $cptid, 'offers_max_id', true );
if ( $colname == 'offercount')
echo get_post_meta( $cptid, 'offers_count', true );
if ( $colname == 'offermaxvalue')
echo get_post_meta( $cptid, 'offers_max_value', true );
if ( $colname == 'dateofend')
echo date("j M y H:i:s", (get_post_meta( $cptid, '_sale_price_dates_to', true )+60*60) );
if ( $colname == 'offerlefttime') {
$atime = time();
$d = (get_post_meta( $cptid, '_sale_price_dates_to', true ) - $atime)/(60*60*24);
$h = ( get_post_meta( $cptid, '_sale_price_dates_to', true ) - $atime - ( (60*60*24) * explode(".", $d)[0] ) )/(60*60);
$m = ( get_post_meta( $cptid, '_sale_price_dates_to', true ) - $atime - ( (60*60*24) * explode(".", $d)[0] ) - ( (60*60) * explode(".", $h)[0] ) )/(60);
echo floor($d) . "d " . floor($h) . "h " . floor($m) . "m";
}
}
add_action('manage_product_posts_custom_column', 'my_cpt_column', 10, 2);
// asl sortowanie
add_filter('manage_edit-product_sortable_columns', 'my_cpt_columns');
function my_sort_metabox( $vars ) {
if( array_key_exists('orderby', $vars )) {
if('OfferId' == $vars['orderby']) {
$vars['orderby'] = 'meta_value';
$vars['meta_key'] = 'offers_max_id';
}
if('Offers' == $vars['orderby']) {
$vars['orderby'] = 'meta_value';
$vars['meta_key'] = 'offers_count';
}
if('Amount' == $vars['orderby']) {
$vars['orderby'] = 'meta_value';
$vars['meta_key'] = 'offers_max_value';
}
if('EndTime' == $vars['orderby']) {
$vars['order'] = 'ASC';
$vars['orderby'] = 'meta_value';
$vars['meta_key'] = '_sale_price_dates_to';
}
}
return $vars;
}
add_filter('request', 'my_sort_metabox');
// asl dodanie kolumny wynikowej z czasem do końca
function my_cpt_column_time( $columns ) {
$columns["offerlefttime"] = "LeftTime";
return $columns;
}
add_filter('manage_edit-product_columns', 'my_cpt_column_time');
And everything nice but one thing doesn't work. I want to have the products sort by column 'EndTime' ASC.
Any suggestions?

Get daily orders count in Woocommerce

I want to get daily order count of daily whenever an order is posted. I wrote the below code to give a notification on slack whenever there is an order. As a result of displaying $result it showing the current order amount rather than the total order count of the day.
function wp_slack_woocommerce_order_status_completed2( $events ) {
$events['woocommerce_order_status_processing'] = array(
// Action in WooCommerce to hook in to get the message.
'action' => 'woocommerce_order_status_processing',
// Description appears in integration setting.
'description' => __( 'Whenever we receive an order', 'slack-woocommerce' ),
// Message to deliver to channel. Returns false will prevent
// notification delivery.
'message' => function( $order_id ) {
$order = wc_get_order( $order_id );
$date = is_callable( array( $order, 'get_date_completed' ) )
? $order->get_date_completed()
: $order->completed_date;
$url = add_query_arg(
array(
'post' => $order_id,
'action' => 'edit',
),
admin_url( 'post.php' )
);
$user_id = is_callable( array( $order, 'get_user_id' ) )
? $order->get_user_id()
: $order->user_id;
if ( $user_id ) {
$user_info = get_userdata( $user_id );
}
if ( ! empty( $user_info ) ) {
if ( $user_info->first_name || $user_info->last_name ) {
$username = esc_html( ucfirst( $user_info->first_name ) . ' ' . ucfirst( $user_info->last_name ) );
} else {
$username = esc_html( ucfirst( $user_info->display_name ) );
}
} else {
$billing_first_name = is_callable( array( $order, 'get_billing_first_name' ) )
? $order->get_billing_first_name()
: $order->billing_first_name;
$billing_last_name = is_callable( array( $order, 'get_billing_last_name' ) )
? $order->get_billing_last_name()
: $order->billing_last_name;
if ( $billing_first_name || $billing_last_name ) {
$username = trim( $billing_first_name . ' ' . $billing_last_name );
} else {
$username = __( 'Guest', 'slack-woocommerce' );
}
}
global $wpdb;
$date_from = '2018-02-27';
$date_to = '2018-02-28';
$post_status = implode("','", array('wc-processing', 'wc-completed') );
$result = $wpdb->get_results( "SELECT count(*) as total 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'
");
// Remove HTML tags generated by WooCommerce.
add_filter( 'woocommerce_get_formatted_order_total', 'wp_strip_all_tags', 10, 1 );
$total = html_entity_decode( $order->get_formatted_order_total() );
remove_filter( 'woocommerce_get_formatted_order_total', 'wp_strip_all_tags', 10 );
//$data2=WC_API_Reports::get_sales_report( );
// Returns the message to be delivered to Slack.
return apply_filters( 'slack_woocommerce_order_status_completed_message',
sprintf(
__( 'Reveived new order with amount *%1$s*. Made by *%2$s* on *%3$s*. <%4$s|See detail> %s', 'slack-woocommerce' ),
$total,
$username,
$date,
$url,
$resullt
),
$order
);
},
);
return $events;
}
add_filter( 'slack_get_events', 'wp_slack_woocommerce_order_status_completed2' );
To get the daily order count you can use this custom function that will return the order count for the current day or the order count for a specific defined date:
function get_daily_orders_count( $date = 'now' ){
if( $date == 'now' ){
$date = date("Y-m-d");
$date_string = "> '$date'";
} else {
$date = date("Y-m-d", strtotime( $date ));
$date2 = date("Y-m-d", strtotime( $date ) + 86400 );
$date_string = "BETWEEN '$date' AND '$date2'";
}
global $wpdb;
$result = $wpdb->get_var( "
SELECT DISTINCT count(p.ID) FROM {$wpdb->prefix}posts as p
WHERE p.post_type = 'shop_order' AND p.post_date $date_string
AND p.post_status IN ('wc-on-hold','wc-processing','wc-completed')
" );
return $result;
}
Code goes in function.php file of your active child theme (or theme). Tested and works.
USAGE:
1) To get the orders count for the current date:
$orders_count = get_daily_orders_count();
2) To get the orders count for a specific date (with a format like 2018-02-28):
// Get orders count for february 25th 2018 (for example)
$orders_count = get_daily_orders_count('2018-02-25');

Woocommerce auto cancel on-hold after X days

Since I will be using offline payments (bank billets - standard in Brazil). What I am trying to achieve is to auto-cancel "on-hold" orders after 9 days, which is when the billet expires. I found a few references of code: one from woocommerce github and another from stackoverflow. What the code does (kinda messy in my opinion) is mirror the "pending" cancelation to "on hild". On github they are saying that it's important to use date_modified arguments to pull orders from the last hour. I have tested this out but it's not working. Do not know what the problem is.
<?php
function wc_foo_cancel_unpaid_onhold_orders() {
global $wpdb;
$held_duration = get_option('woocommerce_hold_stock_minutes');
if ( $held_duration < 1 || 'yes' !== get_option( 'woocommerce_manage_stock')) {
return;
}
$unpaid_orders = wc_foo_cancel_unpaid_onhold_orders( strtotime( '-' . absint( $held_duration) . ' MINUTES'. current_time( 'timestamp')));
if ( $unpaid_orders) {
foreach ( $unpaid_orders as $unpaid_orders ){
$order = wc_get_order( $unpaid_order);
if ( apply_filters( 'woocommerce_cancel_unpaid_order', 'checkout' == $order->get_created_via(), $order ) ) {
$order ->update_status( 'cancelled', _( 'Unpaid order cancelled - time limite reached.', 'woocommerce'));
}
}
}
}
add_action( 'woocommerce_cancel_unpaid_orders', 'wc_foo_cancel_unpaid_onhold_orders');
function wc_foo_get_unpaid_onhold_orders( $date ){
global $wpdb;
$args = array(
'date_modified' => '>' . ( time() - HOUR_IN_SECONDS ),
'status' => 'on-hold',);
$orders = wc_get_orders( $args );
$unpaid_orders = $wpdb->get_col( $wpdb->prepare( "
SELECT posts.id
FROM {$wpdb->posts} AS posts
WHERE posts.posts_type IN ('" . implode( "','", wc_get_order_types()). "')
AND posts.post_status = 'wc-on-hold'
AND posts.date_modified < %s
", date( 'Y-m-d H:i:s', absint( $date)) ) );
}
?>
So I had a little bit of help form #danaharrison at Wordpress.org to achieve this. So the code only applies to 'on-hold' orders.
// To change the amount of days just change '-7 days' to your liking.
function get_unpaid_submitted() {
global $wpdb;
$unpaid_submitted = $wpdb->get_col( $wpdb->prepare( "
SELECT posts.ID
FROM {$wpdb->posts} AS posts
WHERE posts.post_status = 'wc-on-hold'
AND posts.post_date < %s
", date( 'Y-m-d H:i:s', strtotime('-7 days') ) ) );
return $unpaid_submitted;
}
// This excludes check payment type.
function wc_cancel_unpaid_submitted() {
$unpaid_submit = get_unpaid_submitted();
if ( $unpaid_submit ) {
foreach ( $unpaid_submit as $unpaid_order ) {
$order = wc_get_order( $unpaid_order );
$cancel_order = True;
foreach ( $order->get_items() as $item_key => $item_values) {
$manage_stock = get_post_meta( $item_values['variation_id'], '_manage_stock', true );
if ( $manage_stock == "no" ) {
$payment_method = $order->get_payment_method();
if ( $payment_method == "cheque" ) {
$cancel_order = False;
}
}
}
if ( $cancel_order == True ) {
$order -> update_status( 'cancelled', __( 'Pagamento não identificado e cancelado.', 'woocommerce') );
}
}
}
}
add_action( 'woocommerce_cancel_unpaid_submitted', 'wc_cancel_unpaid_submitted' );
/* End of code. */

Categories