Support

Account

Home Forums Front-end Issues pre_get_posts – organising CPT posts with Datepicker field Reply To: pre_get_posts – organising CPT posts with Datepicker field

  • It’s may be just a matter of specifying the post type in the Query.

    It sounds like you know this, but remember… the below code naturally has values that need to be replaced:

    a) ‘my_custom_post_type’ = the ‘slug’ of your post type (3 places… plus the function name twice if desired)
    b) ‘date’ = the ‘name’ of your ACF Date field (1 place)

    
    <?php
    function mycustomposttype_pre_get_posts() {
      if ( is_admin() ) { return $query; }
      if ( is_post_type_archive( 'my_custom_post_type' )  && !empty( $query->query['post_type']  == 'my_custom_post_type' ) {
        $query->set( 'post_type', 'my_custom_post_type' );
        $query->set( 'meta_key', 'date' );
        $query->set( 'orderby', 'meta_value_num' );
        $query->set( 'order', 'DESC' );
      }
      return $query;
    }
    add_action('pre_get_posts','mycustomposttype_pre_get_posts');
    ?>
    

    You may need to adjust ‘orderby’. I got ‘num’ from the ACF docs about querying date fields.