Help us understand the problem. What is going on with this article?

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

やりたいこと

  • 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をカスタムタクソノミー名に変更してください。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした