3

I have to sort the products by price. I'm srugling with this task, because my query works only when any custom taxonomy querying is off. This is query that works, yet it doesn't filter posts by a specific product_category:

$args = array(
    'post_type' => 'product',
    'paged'     => $paged,
    'orderby'   => 'meta_value_num',
    'meta_key'  => 'price',
    'order'     => 'DESC',
);

Now this code:

$args = array(
    'post_type'  => 'product',
    'paged'      => $paged,
    'orderby'    => 'meta_value_num',
    'meta_key'   => 'price',
    'order'      => 'DESC',
    'tax_query'  => array(
        array(
            'taxonomy' => 'product_category',
            'field'    => 'slug',
            'terms'    => $queried_slug
        )
    )
);

It queries the correct category, but doesn't do the sorting at all. I'm not sure how this is even possible.

This is the environment:
Wordpress: 4.4.2
Custom fields management with "Advanced Custom Fields"
Custom post types and taxonomies with "Types"

Here's the SQL that's generated:

SELECT SQL_CALC_FOUND_ROWS  wp_posts.ID FROM wp_posts
LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
LEFT JOIN wp_postmeta sort ON (wp_posts.ID = sort.post_id AND sort.meta_key = 'sort_487')
WHERE 1=1
AND ( 
  wp_term_relationships.term_taxonomy_id IN (487)
)
AND ( 
  wp_postmeta.meta_key = 'price'
)
AND wp_posts.post_type = 'product'
AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'private')
AND ( sort.meta_key = 'sort_487' OR sort.post_id IS NULL )
GROUP BY wp_posts.ID
ORDER BY CAST(sort.meta_value AS SIGNED), wp_posts.post_date DESC LIMIT 0, 18
Swagger
  • 107
  • 8
  • What types/values have `$paged` and `$queried_slug` variables? – Jordi Nebot Nov 22 '16 at 15:42
  • $paged = (int), $queried_slug = (string) – Swagger Nov 22 '16 at 15:47
  • 1
    Could you do a `var_dump` of the `WP_Query` and paste the full SQL? Something odd is going on here. I guess it may be related to some plugin or theme messing up with `pre_get_posts`. – vard Nov 22 '16 at 15:50
  • I've edited the post. Generated SQL is there – Swagger Nov 22 '16 at 17:26
  • @vard see the sql in the post – Swagger Nov 22 '16 at 21:03
  • I just tried out this query, and it's working as expected (posts are ordered by meta value) on a WP installation with ACF pro. So it's probably an other plugin that do some ordering on the results - do you have any post order plugin or something like that? Maybe try out to disable plugins one by one and switch back to default theme to find out the culprit. – vard Nov 23 '16 at 08:09

0 Answers0