Make a custom column sortable, by custom post count

Users are queried differently than posts so you have to hook into the ‘pre_user_query’ action to filter user queries. Let me know if this works:

add_action( 'pre_user_query', 'my_pre_user_query', 1 );
function my_pre_user_query( $query ) {
    global $wpdb, $current_screen;

    // Only filter in the admin
    if ( ! is_admin() )
        return;

    // Only filter on the users screen
    if ( ! ( isset( $current_screen ) && 'users' == $current_screen->id ) )
        return;

    // Only filter if orderby is set to 'art'
    if ( isset( $query->query_vars ) && isset( $query->query_vars[ 'orderby' ] )
        && ( 'art' == $query->query_vars[ 'orderby' ] ) ) {

        // We need the order - default is ASC
        $order = isset( $query->query_vars ) && isset( $query->query_vars[ 'order' ] ) && strcasecmp( $query->query_vars[ 'order' ], 'desc' ) == 0 ? 'DESC' : 'ASC';

        // Order the posts by product count
        $query->query_orderby = "ORDER BY ( SELECT COUNT(*) FROM {$wpdb->posts} products WHERE products.post_type="product" AND products.post_status="publish" AND products.post_author = {$wpdb->users}.ID ) {$order}";

    }

}

Leave a Comment