Created
August 20, 2017 11:37
-
-
Save nczz/be1c470e2fe5c39ada34ac7c816ac12d to your computer and use it in GitHub Desktop.
[WordPress] 使用短碼(shortcode)在網站中區塊顯示文章
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function get_news_posts_shortcode($atts) { | |
extract(shortcode_atts(array( | |
'post_type' => 'news', | |
'posts_per_page' => -1, | |
'order' => 'DESC', | |
'orderby' => 'date', | |
'category_name' => '', | |
), $atts)); | |
$args = array( | |
'post_type' => $post_type, //文章類型 | |
'post_status' => 'publish', //限定為已發布狀態 | |
'posts_per_page' => $posts_per_page, // -1 為不限制撈取數量,若要指定就自行輸入數字 | |
'order' => $order, //排序方式 DESC, ASC | |
'orderby' => $orderby, //根據發文日期排序 | |
); | |
//文章類型為文章時增加判斷分類 | |
if ($post_type == 'post' && $category_name != '') { | |
$args['category_name'] = $category_name; //選取對應分類 | |
} | |
$query = get_posts($args); | |
$html = ''; | |
if ($query) { | |
$html .= '<ul class="news-list">'; | |
foreach ($query as $post) { | |
$url = get_the_post_thumbnail_url($post->ID); | |
$html .= '<li id="post-' . $post->ID . '" class="' . join(' ', get_post_class('', $post->ID)) . '">'; | |
$html .= '<div class="news_img"><img src="' . $url . '"/></div>'; | |
$html .= '<div class="news_content">'; | |
$html .= '<h2><a href="' . get_permalink($post->ID) . '">' . get_the_title($post->ID) . '</a></h2>'; | |
$html .= '<div class="date">' . get_the_date('', $post->ID) . '</div>'; | |
$html .= '<div class="directory">'; | |
$html .= '<h4 class="directory_title">標題</h4>'; | |
$html .= get_the_excerpt($post->ID); | |
$html .= '</div>'; | |
$html .= '<div class="news_link"><a href="' . get_permalink($post->ID) . '">觀看詳情</a></div>'; | |
$html .= '</div>'; | |
$html .= '</li>'; | |
//Demo code 所以寫的比較「豐富」一點,實際上可以省點變數處理,一個 $html .="大家都寫成一行就好" | |
} | |
$html .= '</ul>'; | |
} else { | |
//沒撈到資料的顯示 | |
$html = '無資料顯示'; | |
} | |
wp_reset_postdata(); | |
return $html; | |
} | |
add_shortcode('news-lists', 'get_news_posts_shortcode'); | |
//使用方法:[news-lists posts_per_page="6" post_type="post" category_name="news"] 改顯示六篇就好 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment