11. ITメモ

WordPressで公開日指定で記事を表示

このBlogではテーマごとに記事を分けて登録し、それらを日ごとに一つにまとめたページを作成して、その日の日記形式にしています。これまでタグやカテゴリーを利用して記事をまとめていましたが、タグは個数制限にあい、カテゴリーは増えすぎて使い勝手が悪くなりました。

そこで記事の公開日でまとめることにして、追加のショートコードをGeminiに作ってもらいました。

ショートコード daily_full_content

add_shortcode('daily_full_content', function($atts) {
    // 現在表示している「まとめ記事」自体のIDを取得
    $current_post_id = get_the_ID();

    $atts = shortcode_atts(array(
        'date' => date('Y-m-d'), 
    ), $atts);

    $args = array(
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'post__not_in'   => array($current_post_id), // 自分自身を除外
        
        // 【追加】並び替え設定:タイトル(辞書順)の昇順
        'orderby'        => 'title',
        'order'          => 'ASC',
        
        'date_query'     => array(
            array(
                'year'  => date('Y', strtotime($atts['date'])),
                'month' => date('m', strtotime($atts['date'])),
                'day'   => date('d', strtotime($atts['date'])),
            ),
        ),
    );

    $query = new WP_Query($args);
    if (!$query->have_posts()) return '<p>指定された日付の個別記事は見つかりませんでした。</p>';

    $output = '<div class="daily-full-content-wrapper">';
    while ($query->have_posts()) {
        $query->the_post();
        
        $output .= '<article class="entry-item" style="margin-bottom: 60px; padding-bottom: 40px; border-bottom: 2px solid #000;">';
        $output .= '<h2 style="margin-bottom: 20px; font-size: 1.8em;"><a href="' . get_permalink() . '">' . get_the_title() . '</a></h2>';
        
        // 本文全文を表示
        $content = apply_filters('the_content', get_the_content());
        $output .= '<div class="entry-content-body">' . $content . '</div>';
        
        $output .= '</article>';
    }
    $output .= '</div>';
    
    wp_reset_postdata();
    return $output;
});

1月の記事の公開日がなぜか変わってしまっていて、このコードが使えず、それ用のタグを残さざるを得ませんでした。が、今後はこれを使って運用していこうと思います。

コメント

コメントを残す