Support » Fixing WordPress » WP_Query, query satisfies a custom field and sorted by other values

  • Resolved Tran Cuong

    (@tandoigai)


    Hi
    I’m trying to get posts satisfies a custom field and sorted by other values. For example
    query posts:
    meta_key = _label
    meta_value = product
    but order by ‘_view’, _view is also a meta key.

    I don’t know how to write query like that and I found nothing useful in Codex. Any help? Can I write a query like that by built in functions?

Viewing 2 replies - 1 through 2 (of 2 total)
  • I think this will give you what you are looking for:

    select ‘wp_posts’.’post_title’, ‘wp_posts’.’id’, ‘wp_postmeta’.’meta_value’
    from ‘wp_posts’ left join ‘wp_postmeta’ on ‘wp_posts’.’id’ = ‘wp_postmeta’.’post_id’
    WHERE ‘wp_postmeta’.’meta_key’ = ‘_view’
    ORDER BY ‘wp_postmeta’.’meta_value’

    Oh, thank you. I found the answer for myself

    $args = array(
            'showposts'     => 20,
    	'offset'          => $offset,
    	'cat'       	 =>  $category->term_id,
    	'order'			=>'DESC',
    	'orderby'		=> 'meta_value_num',
    	'post__not_in'	  => array($exclude_id),
    	'meta_key'        => '_view_count',
    	'meta_query' => array(
    	   array(
    	      'key' =>'_label',
    	      'value' => 'product'
    	   )
    	),
    	'post_type'       => 'post',
    	'post_status'     => 'publish',
    	'suppress_filters' => true );
    
    query_posts($args);
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘WP_Query, query satisfies a custom field and sorted by other values’ is closed to new replies.