我們之前創建了主題並添加了標題和導航欄,接下來學習如何用WordPress提供的主循環展示博客文章,我們現在頁面上的博客是寫在HTML中的靜態內容,但是在集成了WordPress的頁面中,所有的內容都應該是動態的。
1、添加主循環
回到我們的index.php文件中,然後轉到container content div的地方,我們把博客的主循環創建在main block div內部。代碼如下:
<div class="main block">
<?php if(have_posts()) : ?>
<?php while(have_posts()) : the_post(); ?>
<article class="post">
<h2><?php the_title(); ?></h2>
<p class="meta">Posted at 11:00 on May 9 by admin</p>
<?php the_content(); ?>
<a class="button" href="#">Read More</a>
</article>
<?php endwhile; ?>
<?php else : ?>
<?php echo wpautop('Sorry, no posts were found'); ?>
<?php endif; ?>
</div>
保存代碼,到前端刷新頁面:
2、添加分類
我們到後臺再添加一篇博客,同時創建一個IT類別,你也可以創建一些其他類別,但它們並不重要。 我們並不是真正處理特定內容,而是僅僅針對示例內容:
你會發現元數據仍然是靜態的,Read More按鈕也是如此,當我們點擊這個按鈕時,它什麼也沒做。
3、添加動態元數據
接下來讓我們解決這個問題。 回到我們的post循環中,找到class =“meta”的p標籤,我們進行以下更改讓它變成動態的。
時間格式化&顯示作者
<p class="meta">
發佈於 <?php the_time('F j, Y g:i a'); ?> by <?php the_author(); ?>
</p>
<?php the_content(); ?>
<a class="button" href="#">Read More</a>
這段代碼與php日期函數的參數有關,the_time(‘F j, Y g:i a’)函數內的參數是爲了將輸出的時間格式化。the_author()會調用博客作者的用戶名。
如果我們希望能夠單擊作者姓名,然後看到該用戶歸檔的所有帖子。 這也很容易做到。 我們只需要提供一個鏈接,如下所示。 在鏈接中,我們輸入php echo get_author_posts_url(),然後傳遞get_the_author_meta()和ID:
<a href="<?php echo get_author_posts_url( get_the_author_meta('ID')); ?>">
<?php the_author(); ?>
</a>
保存代碼,到前端刷新頁面
我們發現作者看不見了,鼠標經過時其變爲黑色。我們進入CSS文件中找到meta類,在article.post .meta下方添加一段樣式將其修復。
article.post .meta a{
color:#fff;
}
獲取文章類別
現在我們希望可以獲得帖子的類別。爲此,我們回到index.php文件,我們來更新代碼,在前面提到的the_author()的a結束標籤之後添加如下代碼塊:
</a>
| Posted In
<?php
$categories = get_the_category();
$separator = ", "; $output = '';
if($categories){
foreach($categories as $category){
$output .= '<a href="'.get_category_link($category->term_id).'">'.
$category->cat_name.'</a>'.$separator;
}
}
echo trim($output, $separator);
?>
</p>
到前端刷新看看:
現在如果我點擊IT,它會把我們帶到類別/IT,你只能看到這個帖子在這裏。
4、削減博客字數&修正Read More按鈕
現在我們想要的最後一件事是文本更短,讓閱讀更多按鈕工作。 因此,我們將轉到我們放置內容的位置,並將其縮短,我們可以將the_content()更改爲the_excerpt(),並修改Read more按鈕的a標籤,如此處所示:
</p>
<?php the_excerpt(); ?>
<a class="button" href="<?php the_permalink(); ?>"> Read More</a>
回到前端頁面刷新,文章變短了
默認縮略字數是55,如果你想調整字數多少,我們在上一個項目中學過,只需在functions.php中加入以下代碼:
// Excerpt Length
function set_excerpt_length(){
return 33;
}
add_filter('excerpt_length', 'set_excerpt_length');
點擊 Read More 按鈕,會跳轉到特定的帖子:
下一節,我們將學習如何添加評論表單以及如何將特色圖片添加到我們的帖子中。