Search code examples
phpwordpressmeta-key

Order post by meta value


I have a custom post type called: business, each post has a metabox with meta key country.

I want to order posts by meta value and only display 3 posts for each meta value:

New york:

  • post title has meta value new york
  • another post title has meta value new york
  • another post title has meta value new york

France

  • post title has meta value France
  • another post title has meta value France
  • another post title has meta value France

PS : Each meta value are generated from another post type places

My code :

$n = 0;
$args = array(
 'post_type'=>'business'
);
$query_biz = get_posts($args);
foreach ($query_biz as $biz) {

    $theme_meta  = get_post_meta($biz->ID,'country',true);

    if($theme_meta == 'France'){

        if($n < 3):
            echo $biz->post_title.'<br/>';
        endif;

    } ...

$n++;

}

Globally I want to separate posts by meta value as this :

New york: <=== meta value |-post title has meta value new york |-another post title has meta value new york |-another post title has meta value new york

France <=== meta value |-post title has meta value France |-another post title has meta value France |-another post title has meta value France

And only limit post result at 3 for each meta value


Solution

  • How about:

    if($n == 0)
      echo $biz->post_title.'<br/>';
    else
      echo '<p>' . $biz->post_title . '</p>;