2013-03-03 69 views
1

我正在爲wordpress中的每個類別創建新頁面。帖子編輯器有一個自定義字段,允許選擇扇區類型,這會在更新時應用於帖子。自定義字段key爲:sector,對於自定義字段meta value選項可以使用SectorA,SectorBSectorC。我正在使用名爲projects的自定義帖子類型。如何通過自定義字段值篩選新的WP查詢?

我在這個環節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 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&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 */ ?> 

感謝您的幫助

回答

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'); 
+0

感謝您的幫助,我試過這個,但它不適合我。現在只顯示標題,下面沒有回覆帖子。 – 2013-03-03 18:49:25

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 } ?>