2016-03-14 63 views
0

我需要通過回帖顯示存檔列表。我創建的插件,此代碼:the_permalink in loop給出了相同的結果

function posts_by_year() { 
    // array to use for results 
    $years = array(); 

    // get posts from WP 
    $posts = get_posts(array(
    'numberposts' => -1, 
    'orderby' => 'post_date', 
    'order' => 'ASC', 
    'post_type' => 'post', 
    'post_status' => 'publish' 
)); 

    // loop through posts, populating $years arrays 
    foreach($posts as $post) { 
    $years[date('Y', strtotime($post->post_date))][] = $post; 
    } 

    // reverse sort by year 
    krsort($years); 

    return $years; 
} 
?> 

<?php function wyswietl_archiwum(){ ob_start(); ?> 

<?php foreach(posts_by_year() as $year => $posts) : ?> 
    <h2><?php echo $year; ?></h2> 
    <ul> 
    <?php foreach($posts as $post) : setup_postdata($post); ?> 
     <li> 
     <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> 
     </li> 
    <?php endforeach; ?> 
    </ul> 
<?php endforeach; ?> 
<?php 
    return ob_get_clean(); 
} ?> 

<?php add_shortcode('archiwum', 'wyswietl_archiwum'); 

當我把簡碼[archiwum]任何頁面上,我得到的名單,但每一個項目顯示當前頁面的標題和鏈接本身。

截圖: screenshot

任何想法如何使它正確?

回答

0

the_permalink()the_title()(和類似功能)使用全局變量$post來確定顯示哪個帖子。由於您的foreach循環處於功能中,因此除了調用setup_postdata($post)之外,還需要更新全局變量$post

documentation細節如下:

setup_postdata(),所以它是你自己做的重要的不分配全局$後變量。如果不這樣做,會導致任何使用上述全局變量的鉤子與$ post全局一起出現問題,因爲它們會引用單獨的實體。

最簡單的方法是在wyswietl_archiwum函數頂部添加global $post;。或者,您可以在foreach循環中執行$GLOBALS["post"] = $post;

+0

這就是'the_date' [記錄](https://codex.wordpress.org/Function_Reference/the_date)的工作方式。該文檔還介紹瞭如何在「特別說明」中獲取所需的行爲。 –

+0

謝謝!我用第二種方法,它的工作原理! –

+0

感謝您對我的第二個問題的快速回答。我騙自己不檢查文檔。我用the_time('d.m')代替。 –