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

有帮助吗?

解决方案

How about:

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

其他提示

How about something like this:

<?php
// New Vars
$posts = array();
$post_limit = 3;

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

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

    // Check if county key exits in array
    if (!array_key_exists($theme_meta, $posts)) $posts[$theme_meta] = array();

    // If more than post_limit don't add
    if ($post_limit <= count($posts[$theme_meta])) continue;
    // Else add post to array
    else array_push($posts[$theme_meta], $biz);

}

// Print Titles
foreach ($posts as $country => $_posts) {
    echo '<h2>Country: ' . $country . '</h2>';

    foreach ($_posts as $post) {
        echo '<p>' . $post->post_title . '</p>';
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top