2013-09-25 111 views
0

我有一個自定義帖子類型,其中包含使用高級自定義字段創建的自定義字段。我可以檢索所有這類的帖子,並用下面的代碼顯示圖像:檢索單個自定義字段的自定義帖子類型

<?php 
$args = array('post_type' => 'image'); 
$loop = new WP_Query($args); 
while ($loop->have_posts()) : $loop->the_post(); ?> 
<?php $image = get_field('image_file'); ?> 
<img src="<?php echo $image['url']; ?>" /> 
<?php endwhile; ?> 

不過,我希望能夠檢索單個圖像的URL,而無需通過所有這些循環。我將如何去做這件事?

我已經試過這樣:

<?php 
$args = array('post_type' => 'image', 'title' => 'Welcome to bird - image 1'); 
$loop = new WP_Query($args); 
while ($loop->have_posts()) : $loop->the_post(); ?> 
<?php $image = get_field('image_file'); ?> 
<img src="<?php echo $image['url']; ?>" /> 
<?php endwhile; ?> 

但它輸出的整個列表 - 我如何才能得到一個帖子?如果有幫助,對固定鏈接是這樣的:

/?image=welcome-to-bird-image-1 
+0

在第二個示例中,爲什麼不再使用WP_Query? –

+0

啊,是的,我應該。我已經更新了它,但我仍然沒有收到單個帖子 - 它顯示了所有這些帖子。 – babbaggeii

回答

0

我現在已經找到了解決辦法:

<?php 
$args = array('post_type' => 'image', 'image' => 'welcome-to-bird-image-3'); 
$loop = new WP_Query($args); 
while ($loop->have_posts()) : $loop->the_post(); ?> 
<?php $image = get_field('image_file'); ?> 
<img src="<?php echo $image['url']; ?>" /> 
<?php endwhile; ?> 

過濾由「形象」的工作,因爲我想要的。

0

可惜你不能使用X_posts表列名作爲WP_Query類的參數,以過濾數據庫的帖子。

唯一的解決方案是使用posts_where篩選器,然後應用常規MySQL代碼來過濾帖子。類似的東西:

function filter_where_title($where = '') 
{ 
    $where .= " OR post_title LIKE '%" . $your_term_here . "%'";     
    return $where; 
} 

$posts = new WP_Query(); 

add_filter('posts_where', 'filter_where_title'); 

注:上面的例子是通用的,你必須爲了申請額外的代碼進行嚴格篩選只有您的自定義後的記錄。上面的代碼也會影響其他帖子類型的查詢。

相關問題