Manohar singh
Manohar singh

Reputation: 509

How to get custom post type by taxonomy id order by meta key sorting

I use woocommerce plugin.

I have products listed by category. I need to list them by price.

I tried this code below :

 $args = array(
    'post_type' => 'product',
    'meta_key' => '_price',
    'orderby' => 'meta_value_num',          
    'order' => $order,
    'tax_query' => array(
    'relation' => 'AND',
                array(
                    'taxonomy' => 'product_cat',
                    'field' => 'id',
                    'terms' => $cid
                )
            )
    );
 $my_query = new WP_Query( $args ); 

The result is not sorted by price, only by id. Is there any solution?

Upvotes: 0

Views: 1736

Answers (1)

Shital Marakana
Shital Marakana

Reputation: 2887

products listed by category

<?php
        $products_category_object= get_queried_object();
        $product_category_taxonomy= $products_category_object->taxonomy;
        $product_category_term_id= $products_category_object->term_id;
        $product_category_name= $products_category_object->name;

        $product_args = array(
        'post_type' => 'product',
        'post_status'  => 'publish',
        'meta_key' => '_price',
        'orderby' => 'meta_value_num', //meta_value Or meta_value_num      
        'order' => 'ASC',
        'tax_query' => array(
                array(
                    'taxonomy' => $product_category_taxonomy,
                    'field' => 'id',
                    'terms' => $product_category_term_id
                )
            ),
        );

        $product_my_query = null;
        $product_my_query = new WP_Query($product_args);
        if( $product_my_query->have_posts() ) 
        {
            while ($product_my_query->have_posts()) : $product_my_query->the_post(); 
                echo get_the_title( $post->ID );
            endwhile;
        }
    ?>

Upvotes: 1

Related Questions