2016-11-27 79 views
2

我試圖通過自定義查詢獲取文章發佈頁面(single.php)上的下一篇文章和以前的文章鏈接。我曾嘗試使用previous_post_link()next_post_link()函數,但他們通過ID獲取帖子。我有我的索引頁下面的循環查詢:獲取下一篇文章和以前的文章鏈接通過WordPress中的自定義查詢

$args = array(
    'post_type' => 'auction_dates', 
    'paged' => $paged, 
    'posts_per_page' => 1, 
    'meta_key' => 'date_of_auction', 
    'orderby' => 'meta_value_num', 
    'order' => 'ASC'); 

正如你所知道的,職位是由自定義字段「date_of_auction」,而不是ID的命令。我想要使​​用該自定義字段而不是ID獲取到單篇文章頁面上下一篇文章和以前文章的鏈接。有任何想法嗎?

回答

0

您可以使用函數get_adjacent_post(),這個函數可以用來檢索下一個和之前的post對象。第三個參數必須設置爲true才能檢索上一個帖子的前一個和假。最後一個參數允許在選定的和受限制的分類中找到相鄰的帖子。

$previous_adjacent_post = get_adjacent_post(true,'',true, 'product_cat'); 
$next_adjacent_post = get_adjacent_post(true,'',false, 'product_cat'); 

if(is_a($previous_adjacent_post, 'WP_Post')){ 
    $previous_link = get_permalink($previous_adjacent_post->ID); 
    $previous_title = $previous_adjacent_post->post_title; 
} 
if(is_a($next_adjacent_post, 'WP_Post')){ 
    $next_link = get_permalink($next_adjacent_post->ID); 
    $next_title = $next_adjacent_post->post_title; 
} 

在這個例子中is_a()條件時,沒有任何反應已發現的錯誤避免(試圖從一個字符串對象作爲響應爲空或null)。

更多細節和例子get_adjacent_post()

最後,您可以使用,過濾器"get_{$adjacent}_post_where":通過自定義字段篩選。

編輯:

隨着你添加的鏈接和解釋,似乎你可以與你使用插件做到這一點:

in_same_meta

表示是否下一個/上帖子必須與當前帖子具有相同的 自定義字段值。您必須通過 自定義字段的名稱進行匹配。舉例來說,如果你有一個自定義字段 名爲「發佈商」,你想下一個/上鍊接導致來自同一出版商 標題:

<?php next_post_link_plus(array('in_same_meta' => 'publisher')); ?> 

請注意,in_same_meta不與自定義字段 排序兼容。如果將order_by設置爲'custom'或'numeric',則禁用in_same_meta中的 。

希望它有幫助!

+0

恐怕沒有任何幫助。我不得不使用這個插件來獲得所需的結果。 http://www.acbrosite.com/plugins/next-previous-post-link-plus-for-wordpress –

+0

我很欣賞這種努力,但代碼對我來說也不起作用。這是什麼給了我正確的鏈接: <?php next_post_link_plus(array('order_by'=>'numeric','meta_key'=>'date_of_auction')); ?> –

+0

我不明白,如果你想使用原生的WordPress功能或只有插件。如果你想用WordPress的功能重現插件行爲,這是可能的,這是另一個問題。 – Benoti

相關問題