I'm developing a plugin and I have made a CPT for events and it has custom fields (one of the fields is for the date).

Everything works fine, Fields and CPT are working and displaying them on the front end works also. But the problem is I can't order my CPT posts by date from the custom field called date_happening.

I have tried to find answer to my problem in many articles, but all of the articles point to the same solution which I tried but for some unknown reason doesn't work for me.

I provide here code.

This is how I create custom fields for my cpt.

  public function register()
      add_action('admin_init', array($this, "atAdminInit"));
      add_action('save_post', array($this, "atSavePost"));

  public function atAdminInit()
    add_meta_box("date_happening-meta", "Date", array($this, "atDateHappening"), "aegeeevents", "side", "low");

  public function atSavePost()
    global $post;

    update_post_meta($post->ID, "date_happening", $_POST["date_happening"]);

  function atDateHappening()
    global $post;
    $custom = get_post_custom($post->ID);
    $date_happening = $custom["date_happening"][0] ?? '';
    <input name="date_happening" type="date" value="<?php echo $date_happening; ?>"/>

And this is what many articles told me how my query arguments should look like to order events by custom field values.

          $args = array(
            'post_type' => 'aegeeevents',
            'meta-value' => 'date_happening',
            'orderby' => 'meta_value',
            'order' => 'DESC',

          $query = new \WP_Query($args);

I have also tried to use 'meta_value_date', 'meta_value_num' etc but without any success. But if I change order values from 'DESC' to 'ASC' then all my posts will come in opposite order so it seems like it's querying by post_date value and completely ignores my args except 'order' argument.

I have also checked how the date_happening field value is saved in the database table wp_postmeta and it seems to be in good format.

enter image description here

I hope everything was understandable and I would appreciate if anyone could help me.

1 Answer 1


You have to use meta_key instead of value to make it order by date_happening metakey

Try this:

'meta_key' => 'date_happening',
'orderby' => 'meta_value',
  • Yep, it worked. Thank you!!
    – user193434
    Commented Aug 20, 2020 at 17:42
  • Great!! No Problem!! Commented Aug 20, 2020 at 17:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.