如何按自定义字段值过滤新的WP_Query?

时间:2013-03-03 15:31:19

标签: categories custom-fields wordpress

我正在为wordpress中的每个类别创建新页面。帖子编辑器有一个自定义字段,允许选择扇区类型,这将应用于更新后的帖子。自定义字段key为:sector,对于自定义字段元value选项,我们可以使用SectorASectorBSectorC。我使用的是名为projects的自定义帖子类型。

我按照此链接http://weblogtoolscollection.com/archives/2008/04/13/how-to-only-retrieve-posts-with-custom-fields/

的建议

如何更改下面代码中的查询行,以便按扇区名称过滤循环,让我们使用SectorA。然后,我会重复使用每个模板页面上的代码,将值更改为其他页面上的SectorBSectorC

我认为这需要以某种方式改变:

$customPosts->query('showposts=5&sector=sectorA&post_type=projects' );

目前,它已成功回传sector valuedescription value,但正在显示所有帖子。所以我尝试使用sector=sectorA将其限制为sectorA似乎不起作用?

此代码位于functions.php中:

function get_custom_field_posts_join($join) {
global $wpdb, $customFields;
return $join . "  JOIN $wpdb->postmeta postmeta ON (postmeta.post_id = $wpdb->posts.ID and postmeta.meta_key in ($customFields)) ";
}
function get_custom_field_posts_group($group) {
global $wpdb;
$group .= " $wpdb->posts.ID ";
return $group;
}

此代码位于模板页面上:

<?php /* Begin Custom Field Posts */ ?>
<h2>Custom Posts</h2>
<ul>
<?php 
global $customFields;
$customFields = "'sector', 'description'";
$customPosts = new WP_Query();
add_filter('posts_join', 'get_custom_field_posts_join');
add_filter('posts_groupby', 'get_custom_field_posts_group');
$customPosts->query('showposts=5&sector=sectorA&post_type=projects' );//Uses same parameters as query_posts
remove_filter('posts_join', 'get_custom_field_posts_join');
remove_filter('posts_groupby', 'get_custom_field_posts_group');

while ($customPosts->have_posts()) : $customPosts->the_post(); 
$sector = get_post_custom_values("sector"); 
$description=  get_post_custom_values("description");?>
<li><?php echo $sector[0]; ?></li>
<li><?php echo $description[0]; ?></li><br />
<?php endwhile; ?>
</ul>
<?php /* End Custom Field Posts */ ?>

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

可能是你想要的

function get_custom_field_posts_join($join) {
global $wpdb, $customSector;
return $join . "  JOIN $wpdb->postmeta postmeta ON (postmeta.post_id = $wpdb->posts.ID and postmeta.meta_key = 'sector' and postmeta.value = '$customSector') ";
}

和修改页面

$customSector='sectorA';//<--- insert this
add_filter('posts_join', 'get_custom_field_posts_join');

答案 1 :(得分:0)

尝试使用此代码。

<?php
$sector = get_post_meta($post->ID, "sector", false);
if ($sector[0]=="") { ?>

<!-- If there are no custom fields, show nothing -->

<?php } else { ?>

<div class="sector">
    <h3>Title</h3>

    <?php foreach($sector as $sector) {
    echo '<blockquote><p>'.$sector.'</p></blockquote>';
    } ?>

</div>

<?php } ?>