如何通过自定义字段值筛选新的WP查询?
问题描述:
我正在为wordpress中的每个类别创建新页面。帖子编辑器有一个自定义字段,允许选择扇区类型,这会在更新时应用于帖子。自定义字段key
为:sector
,对于自定义字段meta value
选项可以使用SectorA
,SectorB
和SectorC
。我正在使用名为projects
的自定义帖子类型。如何通过自定义字段值筛选新的WP查询?
我在这个环节http://weblogtoolscollection.com/archives/2008/04/13/how-to-only-retrieve-posts-with-custom-fields/
跟着意见,我怎样才能更改查询线在下面的代码,以便它通过一个部门的名称过滤循环,让使用SectorA
。然后,我会重新使用每个模板页面上的代码,将值更改为其他页面上的SectorB
和SectorC
。
我认为这需要以某种方式改变:
$customPosts->query('showposts=5§or=sectorA&post_type=projects');
目前,它的回声和sector value
成功description 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§or=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 */ ?>
感谢您的帮助
答
可能这就是你想要什么
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');
答
请尝试使用此代码。
<?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 } ?>
感谢您的帮助,我试过这个,但它不适合我。现在只显示标题,下面没有回复帖子。 – 2013-03-03 18:49:25