Blog

【WordPress】htmlページにWPのRSSを表示する

2016/11/24

Wordpress HTML javascript

備忘録です。

GoogleがAPIの配信を止めると使えなくなりそうです。参考程度でご覧ください。

htmlページにWordpressのRSSフィードを表示する方法です。

基本となるソースコードはこちらから取得できます。
https://developers.google.com/feed/v1/devguide

参考サイト
[Google API] Google AJAX Feed APIによるRSSフィードの新着情報の表示

head内に下記ソースコードを追加
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// JavaScript Document
google.load("feeds", "1");
 
function initialize() {//initialize関数の定義
  var feedurl = 'http://buburinweb.wp.xdomain.jp/feed/';//RSSフィードのURLの定義
 
  var feed = new google.feeds.Feed("feedurl");
  feed.setNumEntries(5);//RSSフィードの表示数
  feed.load(dispfeed);
 
  function dispfeed(result){
    if (!result.error){
      var container = document.getElementById('feed');//divタグ内のid名と対応
      var htmlstr = '';//空の入れ物を用意
 
      htmlstr += '<ul>';//上書きではなく、入れ物に追加
      for (var i = 0; i < result.feed.entries.length; i++) {//RSSフィードの数だけ繰り返す
        var entry = result.feed.entries[i];//配列の定義
        var text = entry.contentSnippet.substr(0,100);
        htmlstr += '<li class=\"blog_list\">';//liタグへのクラスの設定
        htmlstr +=  createDateString(entry.publishedDate);//日付の追加
        htmlstr += '<a href=\"' + entry.link + '\">' + entry.title + '</a> ';//entry内のリンクとタイトルによるリンクの追加
        htmlstr += '</li>';
      }
      htmlstr += '</ul>';
      container.innerHTML = htmlstr;
    }else{//エラーの場合の処理
       alert(result.error.code + ':' + result.error.message);
    }
  }
}
 
//日付表記を変換、月と日の2桁表示
function createDateString(publishedDate){//publishedDateを受け取ったcreateDateString関数の定義
  var pdate = new Date(publishedDate);
  var pday = pdate.getDate();
    if (pday < 10) {pday = "0" + pday;}
  var pmonth = pdate.getMonth() + 1;
    if (pmonth < 10) {pmonth = "0" + pmonth;}
  var pyear = pdate.getFullYear();
  var strdate = pyear + "年" + pmonth + "月" + pday + "日" ;
  return strdate;
}
google.setOnLoadCallback(initialize);
</script>
bodyに下記コードを追加
<div id="feed"></div>
表示を整えるためのCSS
#feed {
    margin-bottom: 20px;
}
#feed li {
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-text-overflow: ellipsis; /* Safari */
    -o-text-overflow: ellipsis; /* Opera */
    white-space: nowrap;
}
#feed li:last-child {
    border: none;
}
.blog_list, .blog_list_old {/**/
    list-style: none;
    padding: 5px 10px;
    color: #000000;
    border-bottom: #000000 1px dashed;
}
.blog_list a {
    margin-left: 10px;
    text-decoration: none;
}
.blog_list a:hover {
    color: red;
}

カテゴリー

月間アーカイブ

MORE

ミュージシャンズ・プラザ

神社仏閣ホームーページ制作

ホームページ制作問合せ