בונים פס חדשות של הזנת RSS להטמעה בכל אתר (News Ticker)

שלום לכם, הבאים והשבים… היום אנחנו בונים ביחד פס חדשות (News Ticker) בעזרת פיד הRSS של YNET אותו נוכל להטמיע בקלות בכל אתר מבוסס PHP.

מדובר על בקשה פופולרית בקרב בוני אתרים אשר מבקשים ליצור פס חדשות בכמה קליקים ובלי לשבור את המקלדת או להכביד על האתר עם המון קוד. הדוגמה נבנתה עבור אתר וורדפרס מבוסס Bootstratp

מה אתם צריכים לדעת?

  • ג'אווה סקריפט (ליתר דיוק jQuery) ברמה מאוד בסיסית
  • שפת PHP ברמה בסיסית או יכולת להעתיק ולשנות מעט
  • הבנה בסיסית של CSS כדי לשנות לעיצוב הרצוי
  • ידע איך להטמיע את הקוד המוגמר באתר שלכם

הדוגמה בה אשתמש נועדה ל..

  • אני יצרתי את הקוד להטמעה באתר וורדפרס
  • אני משתמש בפיד RSS המבזקים של YNET
  • האתר עליו אני מדגים נבנה בעזרת Bootstrap
  • אהבתם? שתפו!

דוגמה של המוצר המוגמר

חדשות אחרונות:

קוד בן שלושה חלקים

הקוד שלנו מורכב משלושה חלקים, הראשון הוא קוד jQuery אשר אחראי על תצוגה מתוזמנת של פריטים ברשימה, השני הוא קוד CSS שאחראי על עיצוב הפריטים והשלישי הוא קוד PHP אשר יקרא את ההזנת RSS בעזרת cUrl וימיר את הפריטים לרשימת HTML

קוד jQuery

// jQuery Bootstrap News Box v1.0.1 
// https://www.jqueryscript.net/slider/Responsive-jQuery-News-Ticker-Plugin-with-Bootstrap-3-Bootstrap-News-Box.html
if (typeof Object.create !== "function") { Object.create = function (e) { function t() { } t.prototype = e; return new t } } (function (e, t, n, r) { var i = { init: function (t, n) { var r = this; r.elem = n; r.$elem = e(n); r.newsTagName = r.$elem.find(":first-child").prop("tagName"); r.newsClassName = r.$elem.find(":first-child").attr("class"); r.timer = null; r.resizeTimer = null; r.animationStarted = false; r.isHovered = false; if (typeof t === "string") { if (console) { console.error("String property override is not supported") } throw "String property override is not supported" } else { r.options = e.extend({}, e.fn.bootstrapNews.options, t); r.prepareLayout(); if (r.options.autoplay) { r.animate() } if (r.options.navigation) { r.buildNavigation() } if (typeof r.options.onToDo === "function") { r.options.onToDo.apply(r, arguments) } } }, prepareLayout: function () { var n = this; e(n.elem).find("." + n.newsClassName).on("mouseenter", function () { n.onReset(true) }); e(n.elem).find("." + n.newsClassName).on("mouseout", function () { n.onReset(false) }); e.map(n.$elem.find(n.newsTagName), function (t, r) { if (r > n.options.newsPerPage - 1) { e(t).hide() } else { e(t).show() } }); if (n.$elem.find(n.newsTagName).length < n.options.newsPerPage) { n.options.newsPerPage = n.$elem.find(n.newsTagName).length } var r = 0; e.map(n.$elem.find(n.newsTagName), function (t, i) { if (i < n.options.newsPerPage) { r = parseInt(r) + parseInt(e(t).height()) + 10 } }); e(n.elem).css({ "overflow-y": "hidden", height: r }); e(t).resize(function () { if (n.resizeTimer !== null) { clearTimeout(n.resizeTimer) } n.resizeTimer = setTimeout(function () { n.prepareLayout() }, 200) }) }, findPanelObject: function () { var e = this.$elem; while (e.parent() !== r) { e = e.parent(); if (e.parent().hasClass("panel")) { return e.parent() } } return r }, buildNavigation: function () { var t = this.findPanelObject(); if (t) { var n = '<ul class="pagination pull-right" style="margin: 0px;">' + '<li><a href="#" class="prev"><span class="glyphicon glyphicon-chevron-down"></span></a></li>' + '<li><a href="#" class="next"><span class="glyphicon glyphicon-chevron-up"></span></a></li>' + '</ul><div class="clearfix"></div>'; var r = e(t).find(".panel-footer")[0]; if (r) { e(r).append(n) } else { e(t).append('<div class="panel-footer">' + n + "</div>") } var i = this; e(t).find(".prev").on("click", function (e) { e.preventDefault(); i.onPrev() }); e(t).find(".next").on("click", function (e) { e.preventDefault(); i.onNext() }) } }, onStop: function () { }, onPause: function () { var e = this; e.isHovered = true; if (this.options.autoplay && e.timer) { clearTimeout(e.timer) } }, onReset: function (e) { var t = this; if (t.timer) { clearTimeout(t.timer) } if (t.options.autoplay) { t.isHovered = e; t.animate() } }, animate: function () { var e = this; e.timer = setTimeout(function () { if (!e.options.pauseOnHover) { e.isHovered = false } if (!e.isHovered) { if (e.options.direction === "up") { e.onNext() } else { e.onPrev() } } }, e.options.newsTickerInterval) }, onPrev: function () { var t = this; if (t.animationStarted) { return false } t.animationStarted = true; var n = "<" + t.newsTagName + ' style="display:none;" class="' + t.newsClassName + '">' + e(t.$elem).find(t.newsTagName).last().html() + "</" + t.newsTagName + ">"; e(t.$elem).prepend(n); e(t.$elem).find(t.newsTagName).first().slideDown(t.options.animationSpeed, function () { e(t.$elem).find(t.newsTagName).last().remove() }); e(t.$elem).find(t.newsTagName + ":nth-child(" + parseInt(t.options.newsPerPage + 1) + ")").slideUp(t.options.animationSpeed, function () { t.animationStarted = false; t.onReset(t.isHovered) }); e(t.elem).find("." + t.newsClassName).on("mouseenter", function () { t.onReset(true) }); e(t.elem).find("." + t.newsClassName).on("mouseout", function () { t.onReset(false) }) }, onNext: function () { var t = this; if (t.animationStarted) { return false } t.animationStarted = true; var n = "<" + t.newsTagName + ' style="display:none;" class=' + t.newsClassName + ">" + e(t.$elem).find(t.newsTagName).first().html() + "</" + t.newsTagName + ">"; e(t.$elem).append(n); e(t.$elem).find(t.newsTagName).first().slideUp(t.options.animationSpeed, function () { e(this).remove() }); e(t.$elem).find(t.newsTagName + ":nth-child(" + parseInt(t.options.newsPerPage + 1) + ")").slideDown(t.options.animationSpeed, function () { t.animationStarted = false; t.onReset(t.isHovered) }); e(t.elem).find("." + t.newsClassName).on("mouseenter", function () { t.onReset(true) }); e(t.elem).find("." + t.newsClassName).on("mouseout", function () { t.onReset(false) }) } }; e.fn.bootstrapNews = function (e) { return this.each(function () { var t = Object.create(i); t.init(e, this) }) }; e.fn.bootstrapNews.options = { newsPerPage: 4, navigation: true, autoplay: true, direction: "up", animationSpeed: "normal", newsTickerInterval: 4e3, pauseOnHover: true, onStop: null, onPause: null, onReset: null, onPrev: null, onNext: null, onToDo: null} })(jQuery, window, document)

jQuery(document).ready(function($) {
	// NEWS TICKER WIDGET
	if($('.newsTicker').length > 0) {
		$(".newsTicker").bootstrapNews({
			newsPerPage: 1,
			autoplay: true,
			pauseOnHover: true,
			navigation: false,
			direction: 'up',
			newsTickerInterval: 10000,
			onToDo: function () {
				//console.log(this);
			}
		});
	}	
});

קוד PHP

<?php
$html		= '';
$feedUrl	= 'https://www.ynet.co.il/Integration/StoryRss1854.xml'; 


$ch 		= curl_init();
$timeout 	= 5; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, $feedUrl);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawFeed 	= curl_exec($ch);
curl_close($ch);

//load the simpleXML object
$xml 		= new SimpleXmlElement($rawFeed);


//iterate through it and build the list
foreach ($xml->channel->item as $item) {     
	$html.= '<li class="animated fadeInRight"><a href="'.$item->link.'" title="'.$item->title.'">'.$item->title.'</a></li>';
}
?>


<div class="newTickerBox">
	<div class="row">
		<div class="col-md-3">
			<div class="bg2 ntlabel w100 text-center"><?php _e('Recent News', THEME_NAME); ?>:</div>
		</div>
		<div class="col-md-9">
			<ul class="newsTicker lsnone p0 m0">
				<?php echo $html; ?>
			</ul>
		</div>	
	</div>
</div>

קוד CSS

/**********************************************
**	NEWS TICKER
/*********************************************/
.newTickerBox .col-md-3 {padding-left: 0;}
.newTickerBox .col-md-9 {padding-right: 0;}
.newTickerBox .newsTicker {background: #3F4652;font-size: 16px; height: 24px !important; overflow: hidden; padding-right: 20px !important;}
.newTickerBox .newsTicker a {color: #fff;}
.newTickerBox .ntlabel {font-size: 16px; text-shadow: 1px 1px 1px #2C6576;} 

מסתבכים עם ההטמעה?

ההטמעה דיי פשוטה למי שיודע מה עושים… בעיקרון אתם צריכים לכלול את הjQuery בקובץ JS שאתם כבר כוללים אל הדף או ליצור קובץ JS ולוודא שאתם כוללים אותו כהלכה אל הדף.

את הCSS יש לצרף אל קובץ הCSS של האתר שלכם ואת קוד הPHP יש להטמיע ישירות במיקום הרצוי כלומר במיקום בו תרצו להציג את פס החדשות.

שימו לב

אני השתמשתי בכל מיני אפקטים של CSS כדי ליצור את אפקט הסלייד שמאלה – אם אתם מתקשים עם זה השתמשו במדור שאלות ותשובות כדי לשאול אותנו על אפקט הCSS הרצוי או איך יוצרים את האפקט הקיים.

טופס התגובות כאן בשבילכם

טופס התגובות כאן, פתוח ומזמין לכל שאלה. אני שמח לעזור (אבל באמת) בתנאי שהשאלה ברורה מספיק – השתמשו בpasteBin כדי להדביק קוד. המון בהצלחה, שגיב SEO.

  • אהבתם? שתפו!