LoginSignup
1

More than 3 years have passed since last update.

WordPressに新着情報を表示するショートコード

Posted at

やりたいこと

  • WordPressの新着情報リストを表示させたい
  • グーテンベルグの機能では日付と記事タイトルしか表示できないので、カテゴリも含めたリストにしたい

表示イメージ

スクリーンショット 2020-03-15 1.18.54.png

出来上がったコード

functions.php
function newsFunc() {
    global $wpdb;
    global $post;
    $news_links = '<ul class="news_links">';
    $news_post = get_posts(array('posts_per_page' => 5,'post_type' => 'post'));
    if($news_post){
        foreach($news_post as $post) : setup_postdata( $post );
        $cat_now = get_the_terms($post->ID, 'category');
        $cat_now = $cat_now[0];
        $now_id = $cat_now->slug;
        $now_name = $cat_now->name;
        $news_links .= '<li><span class="date">'.get_the_time('Y年m月d日').'</span>';
        if($cat_now){
            $news_links .= '<span class="cat '.$now_id.'">'.$now_name.'</span>';
        }
        $news_links .= '<a href="'.get_permalink().'">'.get_the_title().'</a></li>';
        endforeach;
    }
    $news_links .= '</ul>';
    wp_reset_postdata();
    return $news_links;
}
add_shortcode('newsLink', 'newsFunc');
style.css
ul.news_links{
    list-style: none;
}
ul.news_links li{
    display: flex;
    padding: .5em 1em;
    border-bottom: #e4e4e4 1px solid;
    align-items: baseline;
}
ul.news_links li .date{
    width: 7rem;
    font-size: .8em;
    color: #555;
}
ul.news_links li .cat{
    width: 6rem;
    margin-right: 1rem;
    font-size: .7em;
    background-color: #666;
    color: #fff;
    text-align: center;
    padding: 2px 5px;
}
ul.news_links li a{
    width: calc(100% - 14rem);
}
@media screen and (max-width: 599px){
    ul.news_links li{
        flex-wrap: wrap;
    }
    ul.news_links li a{
        width: 100%;
        margin-top: 5px;
    }
}

使い方

表示させたい箇所で[newsLink]というショートコードを追加します。

カスタム投稿で使う場合

functions.phpの'post_type' => 'post'のpostを使用したいカスタム投稿名に変更してください。
表示するカテゴリーをカスタムタクソノミーにする場合は、get_the_terms($post->ID, 'category')のcategoryをカスタムタクソノミー名に変更してください。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1