WordPress: 初步認識 Loop 的功能
這幾天網站的主題換掉,也刪除一些外掛,為了測試各種主題與外掛,我還把網站遷移到我的電腦中,結果再遷移的時候發現,之前裝的備份外掛只能還原不能遷移= =,所以又改裝WPvivid遷移,還好可以完美遷移到我的電腦上,為了遷移又研究半天,折騰一翻之後終於搞定,在本機上測試出喜歡的外掛之後,就直接在伺服器上進行修改。
除了換主題之外,同時也安裝一些新的外掛,並修改一些功能上去,比如說捲動至底下會自動載入文章的功能 (infinite scroll)。我是使用Ajax Load More外掛來加入達成此功能,而且這外掛可以自定你要顯示的內容 (Repeater Templates),裡面也有提供範本讓人修改,但沒付費只能使用一種預設範本。由於預設範本顯示出來的內容和我現在新設定的主題不同,所以我的目標就是把顯示結果變成跟主題相同或雷同。
既然Ajax Load More有提供修改功能,我就直接修改範本,原本想說可以去「主題編輯器」直接複製貼上,就可以顯示出和主題相同的結果,,亂弄的結果就是啥內容都顯示不出來,幸好查了一下WP文件之後,文章 (Post) 的標題、發佈時間、作者等資訊,都可以用WordPress的內建function取得。
The Loop
從官方的文件中,顯示文章的方式就是用 Loop 來實現。而且主題裡的程式碼跟文件中的程式說明挺像的,再來就是從裡面找出我要顯示的內容出來。
一個Loop循環的PHP程式架構如下:
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
//
// Post Content here
//
} // end while
} // end if
?>
從這裡可以看出就是運用while迴圈來取得文章,而迴圈裏面就是放入要顯示的內容。
通常最新文章清單都會含有文章標題、縮圖、發佈時間、作者、分類標籤、摘要等內容。
- 文章標題:
the_title()
- 文章縮圖:
the_post_thumbnail()
- 發布時間:
the_time()
- 文章作者:
the_author()
- 文章分類:
the_category()
- 文章摘要:
the_excerpt()
修改 Ajax Load More Repeater Templates
- 原始範本
預設範本已經秀出縮圖、標題、時間、摘要。
<li class="alm-item<?php if (! has_post_thumbnail() ) { echo ' no-img'; } ?>">
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail('alm-thumbnail');
}?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<p class="entry-meta">
<?php the_time("F d, Y"); ?>
</p>
<?php the_excerpt(); ?>
</li>
- 仿 Ashe 主題
自行把主題的程式碼加進來。
<li class="alm-item<?php if (!has_post_thumbnail()) { ?> no-img<?php } ?>">
<?php if ( has_post_thumbnail() ) { the_post_thumbnail('alm-thumbnail'); }?>
<?php
$category_list = get_the_category_list( ', ' );
if ( ashe_options( 'blog_page_show_categories' ) === true && $category_list ) {
echo '<div class="post-categories">' . $category_list . ' </div>';
}
?>
<?php if ( get_the_title() ) : ?>
<h2 class="post-title">
<a href="<?php esc_url( the_permalink() ); ?>"><?php the_title(); ?></a>
</h2>
<?php endif; ?>
<p class="entry-meta"><?php the_author(); ?> / <?php the_time("Y-m-d"); ?></p>
<?php
if ( ashe_options( 'blog_page_post_description' ) === 'content' ) {
the_content('');
} elseif ( ashe_options( 'blog_page_post_description' ) === 'excerpt' ) {
ashe_excerpt( 50 );
}
?>
<div class="read-more" style="text-align:left;">
<a href="<?php echo esc_url( get_permalink() ); ?>"><?php esc_html_e( 'read more','ashe' ); ?></a>
</div>
<br>
<hr>
</li>
結語
雖然通過外掛來完成無限載入功能,但還是可以通過程式改寫來完成屬於自己的風格,也趁機對WordPress的內部程式有更進一步的認識,希望以後能越來越了解相關程式,做出自己的主題或外掛功能出來。
640 則留言
Scottemips
cialis at canadian pharmacy: TadalAccess – cialis otc switch
JosephSom
buy cialis online without prescription TadalAccess cialis 10mg price
JosephSom
cialis 20 mg coupon tadalafil cost cvs maximum dose of cialis in 24 hours
LorenMep
cialis black 800 mg pill house: Tadal Access – difference between tadalafil and sildenafil
LorenMep
cialis dosage side effects: cialis daily side effects – generic cialis tadalafil 20 mg from india