前言
在使用 WordPress 建置網站時,若頁面內容多以 shortcode 方式組合,想要在頁面中靈活顯示特定文章類型(Post Type)的文章,就需要將查詢文章的功能包裝成 shortcode。這樣可以方便在任何頁面或文章中插入,提升內容管理彈性。本文適合有基礎 PHP 與 WordPress 開發經驗的工程師或自學者。
建立自訂 Shortcode 函式
我們可以在主題的 functions.php 檔案中,撰寫一個函式來查詢指定的文章類型,並輸出 HTML 結構。以下為範例關鍵程式碼說明:
function home_post_listing_shortcode( $atts ) {
ob_start();
// 建立 WP_Query 物件,查詢 post_type 為 'post' 的文章,限制顯示 3 篇,依標題排序(降冪)
$query = new WP_Query( array(
'post_type' => 'post', // 可替換成想抓取的自訂文章類型
'posts_per_page' => 3, // 取出文章數量
'order' => 'DESC', // 排序方式 ASC(小->大), DESC(大->小)
'orderby' => 'title' // 依標題排序
) );
if ( $query->have_posts() ) {
echo '<ul class="info-listing">';
while ( $query->have_posts() ) {
$query->the_post();
?>
<li id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="category_name"><?php the_category(); ?></div>
<?php the_date('Y-m-d at g:ia', '<div class="news_date">', '</div>'); ?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php
}
echo '</ul>';
wp_reset_postdata();
}
return ob_get_clean();
}
註冊 Shortcode
將上述函式註冊為 shortcode,讓 WordPress 辨識並可在頁面中使用:
add_shortcode( 'list-posts-home', 'home_post_listing_shortcode' );
註冊後,只要在 WordPress 後台的頁面編輯器中插入 [list-posts-home],就會顯示該 shortcode 所輸出的文章列表。
實際應用與延伸
- 可修改
post_type參數為自訂文章類型,如product、event等。 - 可加入
category_name或tax_query參數,篩選特定分類文章。 - 調整
posts_per_page與排序條件,符合不同需求。 - 搭配頁面建構器(如 Visual Composer)使用,提升內容排版彈性。
常見坑點
order參數應為DESC(大到小),原範例中寫成DSC會無效。- 使用
the_date()時,若多篇文章同一天只會顯示一次日期,改用the_time()可避免此問題。 - 記得使用
wp_reset_postdata()恢復全域文章資料,避免影響其他查詢。
完整程式碼
function home_post_listing_shortcode( $atts ) {
ob_start();
$query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 3,
'order' => 'DESC',
'orderby' => 'title',
) );
if ( $query->have_posts() ) {
echo '<ul class="info-listing">';
while ( $query->have_posts() ) {
$query->the_post();
?>
<li id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="category_name"><?php the_category(); ?></div>
<?php the_date('Y-m-d at g:ia', '<div class="news_date">', '</div>'); ?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php
}
echo '</ul>';
wp_reset_postdata();
}
return ob_get_clean();
}
add_shortcode( 'list-posts-home', 'home_post_listing_shortcode' );