How can I request messages and use the orderby attribute for orders in the loop according to the meta_value date?

I am creating a website for a theater company and I am creating an index of all past, current and future productions. I would like the index to "order" the end date of each release (field type "date" ACF; "end_date").

Here is an example of my query:

 <?php 
  $futureProd = array(
   'post_type' => 'productions',
   'posts_per_page' => -1,
   'meta_key' => 'ending_date',
   'orderby' => 'meta_value',
   'order' => 'ASC',
 );

 $slider_posts = new WP_Query($futureProd);

 $array_rev = array_reverse($slider_posts->posts);
 $slider_posts->posts = $array_rev;

 ?>

We also tried the following, adding alternatives to "meta_value_date" as well as "meta_value_num":

<?php // query posts
  $futureProd = array(
    'post_type' => 'productions',
    'posts_per_page' => -1,
    'meta_key' => 'ending_date',
    'orderby' => 'meta_value_date',            
    'order' => 'ASC',
  );
?>

and

<?php // query posts
      $futureProd = array(
    'post_type' => 'productions',
    'posts_per_page' => -1,
    'meta_key' => 'ending_date',
    'orderby' => 'meta_value_num',            
    'order' => 'ASC',
  );
?>

No matter what I try, the messages refuse to order them using meta_value and instead order themselves by default, post date.

I am sure that I am missing something simple.

Does anyone have any idea?

0
1

orderby, , meta_value_* : "NUMERIC", "BINARY", "CHAR", "DATE", "DATETIME", 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'.

,

$futureProd = array(
    'post_type' => 'productions',
    'posts_per_page' => -1,
    'meta_key' => 'ending_date',
    'orderby' => 'meta_value_date',
    'order' => 'ASC',
);

$slider_posts = new WP_Query($futureProd);

: YYYY-MM-DD, , posts_orderby STR_TO_DATE MySQL.


YYYYMMDD

function.php ( ). php .

function text_domain_posts_orderby($orderby, $query) {
    //Only for custom orderby key
    if ($query->get('orderby') != 'yyyymmdd_date_format')
        return $orderby;
    if (!( $order = $query->get('order') ))
        $order = 'ASC';
    global $wpdb;
    $fieldName = $wpdb->postmeta . '.meta_value';
    return "STR_TO_DATE(" . $fieldName . ", '%Y%m%d') " . $order;
}

add_filter('posts_orderby', 'text_domain_posts_orderby', 10, 2);

, WP_Query :

$futureProd = array(
    'post_type' => 'productions',
    'posts_per_page' => -1,
    'meta_key' => 'ending_date',
    'orderby' => 'yyyymmdd_date_format', //added custom orderby key
    'order' => 'ASC',
);

.

:

, .

0

Source: https://habr.com/ru/post/1016427/


All Articles