【发布时间】:2014-03-17 13:16:19
【问题描述】:
我想通过自定义字段值显示 wordpress 帖子。这并不难。我已经有了:
<?php
// args
$args = array(
'post_type' => 'safari',
'meta_key' => 'city',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$safari_query= new WP_Query( $args ); ?>
<?php if ($safari_query->have_posts()) : ?>
<?php while ($safari_query->have_posts()) : $safari_query->the_post(); ?>
// My code here
<?php endwhile; ?>
<?php wp_pagenavi(array('before' => '', 'after' => '', 'options' => array(), 'query' => $safari_query)); ?>
<?php endif; ?>
但我现在需要的是,自定义字段值在相关帖子的顶部显示一次。像这样的:
城市 1:
- 酒店1
- 酒店2
- 酒店3
城市 2:
- 4号酒店
- 5号酒店
城市 3:
- 酒店6
等等。
知道如何将其添加到现有代码中吗?
亲切的问候
编辑:
在 Chris 的帮助下,我得到了它,但它每次都显示城市(现在的位置):
<?php
// args
$args = array(
'post_type' => 'resort',
'meta_key' => 'wpcf-location',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$safari_query= new WP_Query( $args ); ?>
<?php if ($safari_query->have_posts()) : ?>
<?php while ($safari_query->have_posts()) : $safari_query->the_post(); ?>
<?php
$location = get_post_meta($post->ID, 'wpcf-location', true);
$resort = the_title();
$previousResort = "";
if($location !== $previousResort ) {
//output the location name and start a list, if necessary close the prvevious list
if($current_row !==1) {
echo "</ul>";
}
echo "$location <br> <ul><li>$resort</li>";
} else {
// not a changed location, just output the resort
echo "<li>$resort</li>";
}
//finally, if this is the last row, close the list
if($current_row == $row_count) {
echo "</ul>";
}
?>
<?php endwhile; ?>
<?php endif; ?>
最终编辑:
在 Chris 的帮助下搞定了!谢谢!
<?php
// args
$args = array(
'post_type' => 'resort',
'meta_key' => 'wpcf-location',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$previousLocation = "";
$safari_query= new WP_Query( $args ); ?>
<?php if ($safari_query->have_posts()) : ?>
<?php while ($safari_query->have_posts()) : $safari_query->the_post(); ?>
<?php
$location = get_post_meta($post->ID, 'wpcf-location', true);
if($location !== $previousLocation ) {
//output the location name and the first resort.
} else {
// not a changed location, just output the resort
}
$previousLocation = $location; ?>
<?php endwhile; ?>
<?php endif; ?>
【问题讨论】: