Ana DEV
Ana DEV

Reputation: 1030

How to order posts by custom field value in wordpress

I wanna order posts by custom field value which now currently is posts view number. I tried with the following code

$queried_object = get_queried_object();
$args = array(
        'post_type'  => 'product',
        'term'  => $queried_object->slug,
        'meta_query' => array(
            array(
                'key'     => 'product_views_count',
                'orderby' => 'meta_value_num',
                'order' => DESC,
            )
        ),
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'terms' => array(
                    $queried_object->term_id
                )
            )
        )
    );
$query = new WP_Query($args);

So with this am getting the current category posts but still it did not sort the posts by product_views_count custom field value.

Any idea what is wrong here? Thanks in advance.

Upvotes: 0

Views: 1354

Answers (1)

William Patton
William Patton

Reputation: 730

I think you have just misplaced the orderby argument. It goes in the top level. You also need to add a meta_key argument there too so it knows what to be ordering by.

I just slightly modified the code from your question to what you need. It's untested but should work just fine.

$queried_object = get_queried_object();
$args = array(
        'post_type'     => 'product',
        'term'          => $queried_object->slug,
        'orderby'       => 'meta_value_num',
        'order'         => DESC,
        'meta_key'      => 'product_views_count',
        'meta_query'    => array(
            array(
                'key'       => 'product_views_count'
            )
        ),
        'tax_query'     => array(
            array(
                'taxonomy'  => 'product_cat',
                'terms'     => array(
                    $queried_object->term_id
                )
            )
        )
    );
$query = new WP_Query($args);

Upvotes: 1

Related Questions