2012-09-26 55 views
1

我想從另一個WordPress的數據庫中最近的帖子在我的footer.php文件,但顯然不理解這個概念。我對WP和「循環」很陌生,所以任何幫助將不勝感激!Wordpress從另一個分區獲得最新的帖子

<!-- .entry-content --> 
<?php 
$originaldb = new wpdb('db_name', 'db_password', 'db_user', 'localhost'); //This has been replaced obviously. 
$newestPost = $originaldb->query("SELECT * FROM wp_posts WHERE post_status = 'publish' ORDER BY post_date DESC LIMIT 0,1;"); 
$newestPost = mysql_fetch_array($newestPost); 
     if ($newestPost) { 
     foreach ($newestPost as $newPost) { 
     ?> 
      <header class="entry-header"> 
       <div class="entry-meta"> 
        <?php echo '<span class="entry-day">'.get_the_date('j').'</span><br><span class="entry-month">'.get_the_date('M').'</span>'; ?> 
       </div> 
       <div class="title-box"> 
        <h2 class="blog-title"><a href="<?php //the_permalink(); ?>"><?php the_title(); ?></a></h2> 
        <?php echo '<a href="'.get_author_posts_url(get_the_author_meta('ID')).'">'.get_the_author().'</a>'; ?> 
       </div> 
       <div class="clear"></div> 
      </header> 
      <div class="entry-content"> 
       <?php the_excerpt(); ?> 
      </div> 
     <?php } //end foreach ?> 
    <?php } //endif ?> 

回答

1

如果我理解你正在試圖做...首先什麼,你不應該需要一個foreach循環,因爲你只打算使用一個結果行。其次,爲什麼不直接訪問$ newestPost的值作爲關聯數組?看看我在哪裏添加了「$ newestPost ['theTitle']」來替換「the_title()」,我也對作者和內容做了類似的處理。

if ($newestPost) { 
     ?> 
     <header class="entry-header"> 
      <div class="entry-meta"> 
       <?php echo '<span class="entry-day">'.get_the_date('j').'</span><br><span class="entry-month">'.get_the_date('M').'</span>'; ?> 
      </div> 
      <div class="title-box"> 
       <h2 class="blog-title"><a href="<?php //the_permalink(); ?>"><?php $newestPost['theTitle']; ?></a></h2> 
       <?php echo '<a href="'.get_author_posts_url(get_the_author_meta('ID')).'">'.$newestPost['theAuthor']).'</a>'; ?> 
      </div> 
      <div class="clear"></div> 
     </header> 
     <div class="entry-content"> 
      <?php echo $newestPost['theContent']; ?> 
     </div> 

    <?php 
    } //endif ?> 

您需要用您的數據庫架構中的任何東西替換'theTitle'等。希望有所幫助,我對WP不太瞭解,所以我可能會錯過重要的東西,但這似乎普遍適用。

編輯:它看起來像使用mysql_fetch_array是no longer recommended

2

以下代碼將給出最後的帖子記錄。

<?php 
$mydb = new wpdb('root','pass','dbname','localhost'); 
$lastpost = $mydb->get_results("SELECT wp_posts.* FROM wp_posts 
WHERE 1=1 
AND wp_posts.post_type = 'post' 
AND (wp_posts.post_status = 'publish') 
ORDER BY wp_posts.post_date DESC LIMIT 0,1"); 

echo $lastpost[0]->post_title; 
?>