wp-graphql / wp-graphql-acf

WPGraphQL for Advanced Custom Fields
https://wpgraphql.com/acf
627 stars 123 forks source link

Error using `orderby` on ACF field and `after` #289

Closed ltroya-as closed 3 years ago

ltroya-as commented 3 years ago

Hi, I am getting an error when I try to sort by an ACF.

This is the code I have at the moment:

/**
 * Adds "published_date" ACF to orderBy available fields
 */
add_filter('graphql_PostObjectsConnectionOrderbyEnum_values', function ($values) {

    $values['published_date'] = [
        'value' => 'published_date',
        'description' => __('The published video date', 'wp-graphql'),
    ];

    return $values;
});

/**
 * Allows to orderby published_date ACF
 */
add_filter('graphql_post_object_connection_query_args', function ($query_args, $source, $input) {

    if (isset($input['where']['orderby']) && is_array($input['where']['orderby'])) {

        foreach ($input['where']['orderby'] as $orderby) {

            if (!isset($orderby['field']) || 'published_date' !== $orderby['field']) {
                continue;
            }

            $query_args['meta_key'] = 'published_date';
            $query_args['orderby'] = 'published_date';
            $query_args['order'] = $orderby['order'];
        }
    }

    return $query_args;
}, 10, 3);

That works like a charm if I get all the results in one query but I want to implement an infinity scrolling feature on my app.

When I try to use after to get the next results, I got this error:

[Unknown column 'wp_posts.published_date' in 'where clause']
SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND ( wp_postmeta.meta_key = 'published_date' ) AND wp_posts.post_type = 'video' AND ((wp_posts.post_status = 'publish')) AND wp_posts.published_date <= "2015-01-01 12:00" AND ( wp_posts.published_date < "2015-01-01 12:00" OR ( wp_posts.ID < 1284280 ) ) GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value DESC, wp_posts.ID DESC LIMIT 0, 21

This is my query:

query getVideos {
  videos(
    first: 20
    after: "YXJyYXljb25uZWN0aW9uOjEyODQyODA"
    where: { orderby: { field: published_date, order: DESC } }
  ) {
    pageInfo {
      hasNextPage
      endCursor
    }
    nodes {
      videos {
        publishedDate
      }
    }
  }
}

I know what the error means and it's right but I don't know how to solve this. Can you give me some hints to solve this problem?

ltroya-as commented 3 years ago

I make a mistake, it was:

$query_args['orderby'] = 'meta_value_num';