2017-04-13 52 views
1

在wordpress中,我試圖獲取當前行的id和即將到來的行的下一個id。在WordPress的foreach循環中,返回當前行ID和next/prev行ID

示例數據庫:

----------------------------- 
    | id | book | orderby | 
    ----------------------------- 
    | 3 | b |  1 | 
    ----------------------------- 
    | 1 | f |  2 | 
    ----------------------------- 
    | 2 | g |  3 | 
    ----------------------------- 

代碼:

$entries = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."_books" ORDER BY orderby ASC); 
foreach ($entries as $print){ 
    $prev = //on second row this would be 3 
    $current = $print->id //on second row this would be 1 
    $next = //on second row this would be 2 
} 

我覺得沒有WordPress的方式,你只會增加或減少循環數組的鍵。這是prolly簡單的修復。

+0

'的var_dump($項)' - 我猜你有一個數組? – Tom

+0

是的,它是數組 – user1203497

+1

你有沒有使用'$ wpdb-> get_results'而不是'WP_Query'或甚至'get_posts'的原因? – Frits

回答

2

您可以使用類似以下內容:

<?php 

$entries = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."_books ORDER BY orderby ASC"); 
$entries = array_values($entries); //shouldn't be needed, but used just in case wordpress returns a non-incrementing key structure for whatever reason 

foreach ($entries as $k=>$v) { 
    if (isset($entries[$k - 1])) { 
     $prev = $entries[$k - 1]->id; 
    } 
    else { 
     $prev = null; 
    } 

    $current = $v->id; 

    if (isset($entries[$k + 1])) { 
     $next = $entries[$k + 1]->id; 
    } 
    else { 
     $next = null; 
    } 
} 

?> 
+0

是的,這是有效的。謝謝! – user1203497

+0

+1 - 這幾乎就是我想要達到的目標,但是你打敗了我。下次可能會輸入一點慢一點;)幹得好! – Frits