0

I'm trying to add a date range filter for wordpress admin users table to filter users that have posted ads between the selected range. I've managed to add the date range inputs.

enter image description here

I have 2 issues with this approach.

  1. When I hit filter the selected date doesn't bind to the query (like date_from=2018-11-28), with the text input.

    <input type="text" id="date-from" name="date_from" autocomplete="off">

    Then I used a hidden select input with the same name and set the value using jquery when date input is changed.( This is not good, but solve the issue)

    What's the issue with the input. Can't I use a text input in filters ?

  2. To add the filter query I used pre_get_users . But it doesn't filter users

    add_filter( 'pre_get_users', 'filter_users' );
    function filter_users( $query ) {
    global $pagenow;
    
    if ( is_admin() &&  'users.php' == $pagenow && isset( $_GET[ 'date_from' ] ) || isset( $_GET[ 'date_to' ] ) ) {
    
        $date_from = isset( $_GET[ 'date_from' ] ) ? $_GET['date_from'] : null;
        $date_to = isset( $_GET[ 'date_to' ] ) ? $_GET['date_to'] : null;
    
        $date_where = '';
    
        if( ! empty($date_from) > 0 && ! empty($date_to) > 0){
            $date_where = "DATE(wp_posts.post_date) >= '$date_from' AND DATE(wp_posts.post_date) < '$date_to'";
        }else if( ! empty($date_from)){
            $date_where = "DATE(wp_posts.post_date) >= '$date_from'";
        }else if( ! empty($date_to)){
            $date_where = "DATE(wp_posts.post_date) < '$date_to'";
        }
    
        if( empty($query->query_where) ){
            $query->query_where = "INNER JOIN wp_posts ON wp_posts.post_author = wp_users.ID WHERE $date_where";
        }else{
    
            $query->query_where = str_replace( "WHERE 1=1', 'INNER JOIN wp_posts ON wp_posts.post_author = wp_users.ID WHERE 1=1 AND $date_where", $query->query_where);
        }
    
    }
    }
    

What is the reason for this issue.

Thanks in advance

  • A sidenote, but your queries don't check the post type of the posts, so they'll pick up posts, pages, attachments, nav menu items, autosaves, revisions, etc etc – Tom J Nowell Nov 30 '18 at 4:24
  • @TomJNowell Thank you for the note. But It should return empty if I choose a future date. right? It's not – Malinda Nov 30 '18 at 4:55
  • Used pre_user_query instead of pre_get_users and i'ts working – Malinda Dec 14 '18 at 5:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.