最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

custom field - How to adjust meta value to UTC time in WP Query

programmeradmin7浏览0评论

I'm displaying three lists of events on my site: past events, current events, and future events. The lists are sorted by a custom date time field. The code I have is currently working, but Wordpress is sorting based on the UTC time zone, instead of the chosen local time zone. Here's the code I'm using for the custom queries:

function sort_current_events( $query ) {
    $query->set( 'post_type', [ 'events' ] );
    $query->set( 'order', 'DESC');
    $query->set( 'orderby', 'meta_value' );
    $query->set( 'meta_key', 'event_time' );
    $query->set( 'meta_type', 'DATE' );
    $query->set( 'meta_value', date( "Ymd" ) );
    $query->set( 'meta_compare', '=' );
}
add_action( 'elementor/query/current_events', 'sort_current_events' );

function sort_upcoming_events( $query ) {
    $query->set( 'post_type', [ 'events' ] );
    $query->set( 'order', 'DESC');
    $query->set( 'orderby', 'meta_value' );
    $query->set( 'meta_key', 'event_time' );
    $query->set( 'meta_type', 'DATE' );
    $query->set( 'meta_value', date( "Ymd" ) );
    $query->set( 'meta_compare', '>' );

}
add_action( 'elementor/query/upcoming_events', 'sort_upcoming_events' );

function sort_past_events( $query ) {
    $query->set( 'post_type', [ 'events' ] );
    $query->set( 'order', 'DESC');
    $query->set( 'orderby', 'meta_value' );
    $query->set( 'meta_key', 'event_time' );
    $query->set( 'meta_type', 'DATE' );
    $query->set( 'meta_value', date( "Ymd" ) );
    $query->set( 'meta_compare', '<' );


}
add_action( 'elementor/query/past_events', 'sort_past_events' );

I'm using Elementor, which is why the custom queries are written in this format, but Elementor just hooks into the normal WP Query function so all the properties here would work the same if it was written in the normal WP Query syntax.

The problem I have is that the custom date field is in the local time zone, and by default it seems that when Wordpress uses 'meta_compare', it is using UTC time instead of the local time zone chosen in the Wordpress settings.

Is there a way that I can convert the custom field values to UTC time within the query functions so the sorting is accurate? Or some way to compare using local time? These custom field values are also displayed on the front-end in the local time zone, so I need the original values to stay in local time.

I also need to make sure that my solution is resilient to edge-cases such as daylight savings time.

发布评论

评论列表(0)

  1. 暂无评论