1

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

我遵循了此链接http://weblogtoolscollection.com/archives/2008/04/13/how-to-only-retrieve-posts-with-custom-fields/上的建议

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

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

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

目前它成功地呼应了sector value并且description value显示了所有帖子。所以我尝试将其限制在扇区A 使用sector=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 */ ?>

谢谢你的帮助

4

2 回答 2

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');
于 2013-03-03T17:37:37.897 回答
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 } ?>
于 2013-04-21T16:31:37.863 回答