LoginSignup
2
3

More than 5 years have passed since last update.

WordPress RSS記事を取得

Last updated at Posted at 2018-09-10

マルチサイトにして親サイトの記事を取得するときはSQLを使っていたけど
RSSを使ったら更新まで時間がすこーしかかるけど便利だったので備忘録。
これなら違うドメインでも取得出来る。

news-list.php
<div class="list-box">
    <?php
    include_once(ABSPATH . WPINC . '/feed.php');
    $rss = fetch_feed(array( //複数サイトを取得したい時
        'https://hogehoge.com/?feed',
        'https://hoge.com/?feed=rss2&cat=1,2' //カテゴリーを指定したい時
    ));
    if (!is_wp_error($rss)) {
        $rss->set_cache_duration(1800);
        $rss->init();
        $maxitems = $rss->get_item_quantity(5); //5つ記事を出力する
        $rss_items = $rss->get_items(0, $maxitems);
        date_default_timezone_set('Asia/Tokyo');
    }
    ?>
    <?php if (!empty($maxitems)) : ?>

    <?php if ($maxitems == 0) {
        echo '<li>RSSデータがありませんでした.</li>';
    } else {
        foreach ($rss_items as $item) :;
    } ?>


    <a href="<?php echo $item->get_permalink(); ?>">
        <div class="list-img"><!--画像を表示-->
            <?php 
            $first_img = '';
            if (preg_match('/<img.+?src=[\'"]([^\'"]+?)[\'"].*?>/msi', $item->get_content(), $matches)) {
                $first_img = $matches[1];
            } ?>
            <?php if (!empty($first_img)) : ?>
            <img src="<?php echo esc_attr($first_img); ?>" class="news-thumbnail">
            <?php endif;  ?>
        </div>
        <div class="list-text">
            <span class="list-cat"><!--カテゴリーを表示-->
                <?php if ($category = $item->get_category()) {
                echo esc_html($category->get_label());
            }; ?>
            </span>
            <span class="list-date"><!--日付をを表示-->
                <?php echo $item->get_date('Y/m/d');?>
            </span>
            <?php
            $days = 3; //Newを表示させたい期間の日数
            $today = date_i18n('U');
            $entry = $item->get_date('U');
            $kiji = date('U', ($today - $entry)) / 86400;
            if ($days > $kiji) {
                echo '<font color="#ff0000">&nbsp;New!</font>';
            }
            ?>
            <h2>
                <?php echo $item->get_title();  ?><!--記事のタイトルを表示-->
            </h2>
            <span class="list-des"><!--記事を40文字分出力する-->
                <?php echo mb_substr(strip_tags($item->get_description()), 0, 40); ?>・・・</span>
        </div>
    </a>

    <?php endforeach; ?>
    <?php endif; ?>
</div>

htmlとかcssはお好みで変えてください。

2
3
0

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
2
3