Following on from the post Display Your WordPress Recent Posts on a Static Page which was used to display your WordPress posts on a non-WP website on the same server. I have had several people contacting me on how to display WordPress posts on another WordPress blog. This tutorial will show you how to display your posts, associated post thumbnail images and a snippet of the content from one blog to another by fetching the data from your RSS feed using the SimplePie RSS parser which is included in the WordPress installation.
Enable Post Thumbnails in WordPress & RSS Feeds
To be able to display the post thumbnails you need to enable or check that your theme supports thumbnails and also enable post thumbnails to show up in your RSS feeds.
To display your post thumbnails in your feeds you need to add the following to your theme’s functions.php
<?php //add post thumbnails to RSS images function cwc_rss_post_thumbnail($content) { global $post; if(has_post_thumbnail($post->ID)) { $content = '<p>' . get_the_post_thumbnail($post->ID) . '</p>' . get_the_excerpt(); } return $content; } add_filter('the_excerpt_rss', 'cwc_rss_post_thumbnail'); add_filter('the_content_feed', 'cwc_rss_post_thumbnail'); ?>
Whilst functions.php is open check for or add the following
add_theme_support( 'post-thumbnails' );
Don’t forget to add the thumbnails to your posts!
Code to Display WordPress Posts
Open up your theme template and add the following snippet of code
<?php $rss = fetch_feed('https://www.worldoweb.co.uk/feed'); if (!is_wp_error( $rss ) ) : $maxitems = $rss->get_item_quantity(5); $rss_items = $rss->get_items(0, $maxitems); endif; ?> <?php function get_first_image_url($html) { if (preg_match('/<img.+?src="(.+?)"/', $html, $matches)) { return $matches[1]; } } ?> <?php function shorten($string, $length) { $suffix = '…'; $short_desc = trim(str_replace(array("/r", "/n", "/t"), ' ', strip_tags($string))); $desc = trim(substr($short_desc, 0, $length)); $lastchar = substr($desc, -1, 1); if ($lastchar == '.' || $lastchar == '!' || $lastchar == '?') $suffix=''; $desc .= $suffix; return $desc; } ?> <ul class="rss-items" id="wow-feed"> <?php if ($maxitems == 0) echo '<li>No items.</li>'; else foreach ( $rss_items as $item ) : ?> <li class="item"> <span class="rss-image"> <?php echo '<img src="' .get_first_image_url($item->get_content()). '"/>'; ?> </span> <span class="data"> <h5><a href='<?php echo esc_url( $item->get_permalink() ); ?>' title='<?php echo esc_html( $item->get_title() ); ?>'> <?php echo esc_html( $item->get_title() ); ?></a></h5> <span class="date-image"> </span><small><?php echo $item->get_date('F Y'); ?> </small> <span class="comment-image"> </span><small><?php $comments = $item->get_item_tags('https://purl.org/rss/1.0/modules/slash/', 'comments');?><?php $number = $comments[0]['data']; ?> <?php if ($number == '1'){ echo $number." ". "Comment"; } else {echo $number. " "."Comments";}?></small> <p><?php echo shorten($item-> get_description(),'150');?></p> </span> </li> <?php endforeach; ?> </ul>
Now we need to edit the above snippet to suit your needs. I have highlighted the lines that need to be changed. I recommend that you get the script running before making any other changes and always test it in a development environment and not in a production environment.
Line 2 Change this to the URL of the feed you want to fetch.
Line 7 Gets the latest 5 posts. This can be changed to suit your needs.
Line 11-17 This function grabs the first image that is contained in the feed.
Line 18-29 This function is used to shorten the description and not display the full blog post.
Line 30 This is the start of our output which is in the form of an unordered list.
Line 36-38 This is where our image from the post thumbnails feature should display. Please note that linking to an external blog which is not your own may result in no images being displayed.
Line 41 get_date(‘F Y’); This will display the date of the published content. This can be changed to suit your requirements. Read Formatting Date and Time to learn more.
Line 42-43 grabs the amount of comment(s) the post has received. This may not show up as it depends on your RSS feed structure.
Line 44 shorten($item-> get_description(),’150′) uses the function shorten (Line 19-29) to display the blog post to a maximum of 150 characters. This can be changed to suit your requirements.
Add the CSS
Now it’s time to spice up the content with a little CSS. Open up your stylesheet, normally style.css in WordPress. Feel free to change any of the CSS to suit your requirements.
#wow-feed { background: #FFFFFF; border: 1px solid #AFAFB0; width: 600px; margin: 10px 0; font-size: 0.8em; } #wow-feed li { list-style: none; } #wow-feed .rss-image img { width: 100px; height: 100px; padding: 8px; border: solid 1px #eee; } #wow-feed .rss-image { width: 30%; } #wow-feed .item { border-bottom: 1px solid #AFAFB0; padding: 10px; } #wow-feed .data { display: inline-block; margin-left: 2%; vertical-align: top; width: 70%; } #wow-feed .data h5 { font-weight: bold; } #wow-feed .data small { color: #8F90CB; font-size: 0.9em; margin-right: 10%; } #wow-feed .comment-image { background: url("images/comments.png"); height: 16px; width: 16px; vertical-align: middle; display: inline-block; margin-right: 2%; } #wow-feed .date-image { background: url("images/date.png"); height: 16px; width: 16px; vertical-align: middle; display: inline-block; margin-right: 2%; }
All you need to do now is to add the images to your theme images folder. I have packed the tutorial and image files into a handy zip file, available below. If the comments and time images do not display you will need to change the image paths in the CSS to be relative to your theme image directory.
Download
Conclusion
This method of displaying your posts in another blog is fairly limited as there is only so much information contained in a RSS feed. If you have any questions or maybe have a better solution feel free to comment.
Sources
Use SimplePie to grab first image from a RSS feed
Discover more from WorldOWeb
Subscribe to get the latest posts sent to your email.
Dear Tracy Ridge,
Thanks for great post !
I have 2 wordpress blog sites: Site A and Site B, both of them were put on the same hosting. Database of Site A has prefix is sitea_ and Database of Site B is siteb_. Site B has 4 categories which is B1,B2,B3,B4. How do i do to show 5 newest posts in B1 of site B on site A ? Thanks so much again !
I will see if I can replicate the scenario and I will get back to you.
I have found a way but unfortunately it is very buggy. The next version of WordPress will upgrade to the latest version of SimplePie which should make things much better then I’ll let you know more.
Hey, thanks so much for this. I just used it with the adapt responsive theme to pull posts from my other blog. I don’t know what I would’ve done without this post. Thanks, again!
Good information , thanks for sharing
Hey Tracy,
I have an error : No items found. Whats might be the problem? I made everything same.as you.
Hi Anna. Have you published anything on your blog? What is your URL and what are you linking to?
This is awesome! Is there any way to use the featured image instead?
hello,
I’ve searched all the internet lol and nothing so far, could someone explain in the css how I can display the rss feed as shown in the image?
Everyting is working but I can get the image to align to the text
I’ve tried with tables and nothing
Help:::!
thanks
Have you added the CSS from the post? I suggest you install the Firebug extension or use your browser debugger to play around with the CSS then make the changes permanently when you are happy. A tip for the CSS is to make small changes and ensure that you do a full browser refresh as your browser may use a cached stylesheet. Can you provide me with a URL and I’ll take a look?
hi again, this is a question that may actually solve my previous error issue, where exactly is the code supposed to go. I have a index.php and a home.php for my theme. the home.php is where the blog posts appear on the homepage. index.php shows the structure (header, maincontent, footer, etc)
Also is it possible for when you click on the title that comes in on the rss feed to open the blog post in a new window?
Generally the code can go into any template. It depends on where you want it positioned. Just be careful not to place it in the loop! You can also display it using a widget in the sidebar with the following plugin: https://wordpress.org/extend/plugins/allow-php-in-posts-and-pages/
You then add the code directly to the widget.
To open the page in a new window or tab add the following to the a tags. Example below.
Ignore the nofollow just add target=”blank”
Well at first I thought it was working, but I get a error message whenever I try to create a new post or trash one.
Warning: Cannot modify header information – headers already sent by (output started at /homepages/44/d393976557/htdocs/wp-content/themes/DelicateNews/functions.php:17) in /homepages/44/d393976557/htdocs/wp-includes/pluggable.php on line 881
any suggestions?
That particular error is your functions.php. You must have some whitespace either before or after (or both) the php opening and closing tags. Delete the spaces and the error should go away.
Hello, I must say your code is awesome! I have been looking for something like this for over year. I decided to do a search again today and your post came up! 🙂
I would like to know how would I include a read more link. On my current website, we have read more links at the bottom of each description or excerpt. Could you tell me how to add it in this code. I believe it’s called pagination.
Simply add the following underneath the description (excerpt).
Then you can style the read-more class in your css file. An example would be.
The code works perfect for me but I want the image to be of a custom size. I have custom sizes set up for my thumbnails but when I change it in the code I always get the big image in the RSS:
[code]
if ( function_exists( ‘add_image_size’ ) ) add_theme_support( ‘post-thumbnails’ );
if ( function_exists( ‘add_image_size’ ) ) {
add_image_size( ‘home1-thumb’, 630, 320, true );
}
function cwc_rss_post_thumbnail($content) {
global $post;
if(has_post_thumbnail($post->ID)) {
$content = ” . get_the_post_thumbnail($post->ID,’home1-thumb’) .
” . get_the_excerpt();
}
return $content;
}add_filter(‘the_excerpt_rss’, ‘cwc_rss_post_thumbnail’);
add_filter(‘the_content_feed’, ‘cwc_rss_post_thumbnail’); [/code]
Are you getting any error messages? Have you tried adding a width to the img tag?
Hey, thank you for this. I was looking for something like this for long time. I have a one question if it is not problem and if i am not bothering you. Is there a way i can offset first item like in regular loop. I mean is there way to filter out first post from the rss feed? Thank you for your time
Hey, I allredy figured it out. Sorry for bothering
No bother at all. Glad you figured it out. Feel free to share your code with others, just remember to wrap them in pre tags.
Ok, so if anyone had this problem here is the solution, if you want to filter one or few latest posts you can do that in line 8 from zero to number of posts you want to exclude, for example if you want your lood exclude 4 latest posts from feed, your line 8 should look like this
Separate question. (I am going to have to buy you a beer.) Do you see new posts immediately after publishing? It seems to taks 2 hours for new posts to show.
You are lucky I like Beer. 😉 The cache is set at 3600 seconds. To change it add the following underneath the feed include:
Where to add this code?
I mean where is the feed include file?
Ritesh – Have you looked at
https://pastebin.com/eRh4hbjY
What is it you are trying to do?
Anyone else have an issue where get_description() with get_content() only pull an excerpt? I’m having a hard time pulling full post.
Have you enabled; for each article in a feed, show full text in the WordPress Reading Settings.
I have, unfortunately. Do you think it may have something to do with the WordPress installation being on a subdomain?
Is the full content in the XML feed? Have a look at the source file
I have checked it with feed burner and it shows the excerpt with read more link. I am starting to wonder if it is because of the way the posts are display on the blog…
It could be a theme related problem? Which theme are you using?
hi : Tracy Ridge
Can I get code to bring from some Categories
thanks
Get posts from categories or display the category?
display the category
@ayman Place within the loop to display your categories
“Please note that linking to an external blog which is not your own may result in no images being displayed.”
Does something have to be enabled on the external blog? Images are not getting pulled.
If it is a WP blog and its your own then just make sure you use the post-thumbnails feature and add the snippet in functions.php. If you wanted to link to another blog, let’s say http://www.smashingmagazine.com then you could only pull an image if they have used one. There is no guarantee.
The below snippet was already in functions.php – Maybe the image not being pulled because it is in the post body? It is outputting
add_theme_support( ‘post-thumbnails’ );
Do you have a URL?
Try changing
To
To try and fetch the first available image within the content
Hi, making use of the built-in lirairbes within WordPress (mainly Transients and HTTP API) would make this code much simpler and more portable.Here’s a quick one shot of how it could work: https://gist.github.com/900356
This code has helped me out immensely, thank you.
How can I display the entire blog post? First I tried changing the shorten value to 1000, but it seems to be pulling the excerpt.
Next I tried removing the shorten function and echoed get_description() – but this threw back a php error.
Any advice?
Thanks, again.
Steve
Oh, simply replace get_description with get_content().
🙂 Thanks, again.
Glad you figured it out. Sometimes it just takes a little perseverance to get the desired result. It’s a great way to learn.
hi : Tracy Ridge
Thanks it works
Great work
Thank you
No problem
hi :
How to include in Widgets?
thanks
Unless you want to hard-code it into your theme I suggest you try this plugin
i try
thanks
yes i add images to my blog posts I used PHP Code widget Plugin to Insert code and i test in two themes
same problem
Strange, I got it working first time. Try testing it on the TwentyEleven theme? If that fails then copy the code from the post into the widget and try again. If that works switch back to your theme and test it again. If that fails then it is a theme problem.
i Try testing it on the TwentyEleven theme same problem
Did you try re-entering the code again into the widget? How did you copy the code to the widget? Have you used any other RSS plugin?
I use your feed code to testing
look what i do
I think it makes sense now. U are trying to add 2 widgets with the code in? If I am right you need to strip the functions from one of the widget as they are declared twice, hence the error. Remove the following code from 1 of the widgets and try again.
hi : Tracy Ridge
I Remove the following code from 1 of the widgets and try again. and working now .
can i used this code now
Is there any other tips.
thank you
hi : Tracy Ridge
I used PHP Code widget it,s good working but when i add Second file php i see this problem
what i can do?
thanks
I will test it out myself and let you know the outcome. Did you add images to your blog posts?
I have tested it myself and it works perfectly. Have you removed all the code from the Display your latest posts on a static page from your templates. What theme are you using?
hi : Tracy Ridge
thank i like this code but photo is emty how can show it?
thanks
Wow, great article, I really appreciate your thought process and having it explained properly, thank you!
Hey man!
Thanks for this but do you know how to put the ‘post author’ in there too??
Thanks,
Luke
Hi Luke. Try adding this:
Hi Tracy, thanks for this – worked perfectly!
Your welcome 😉
not working
Try the following: https://pastebin.com/mfmdypzi The code above was made a little messy with Disqus
great thanks
one question….
how to get author id?
You will find all the available functions here https://simplepie.org/api/class-SimplePie_Author.html
When working with RSS feeds there is only a certain amount of Author data that can be taken from them, not sure about ID, other than name.
I’m not 100% positive but WP might not use the full SImplePie Library either. Looking through the class.simplepie code may also be beneficial. https://core.trac.wordpress.org/browser/tags/4.4.1/src/wp-includes/class-simplepie.php
How to display posts for a specific author?
This would be difficult but not impossible, although I haven’t tested that theory. It could be possible to filter the data before you get to the Foreach loop, however it would also add more strain on the server. If I have time over the weekend I’ll try it out.
I have three questions…
1) how to get all category?
2) how to get all tags?
3) how to set feature image?
https://pastebin.com/qYkyr3eH
If you look at the structure of your RSS feed you may see that your tags are also displayed as categories. There are no featured images in RSS so the script fetches the 1st image inside the content. As this is only RSS there is only so much data you can pull from it!
great…
but how to link tags?
Here is a simple way – Remove previous tag code first and read comments in the paste https://pastebin.com/AxKyYNDY
I will have a look into getting the URL from the feed instead of setting it manually.
© 2024 WorldOWeb. All rights reserved