How to display WordPress RSS feed your website? - wordpress

Hello i have a website and a blog, i want to display my self hosted wordpress blog on my website.
I want to show only 3 post on my website.
I want to automatically check for any new post everytime when i reload my website, so that the recent three gets displayed only.
I want to show the complete title of my wordpress blogpost but specific letters of description.
Also the description should end up with a word not some piece of non-dictionary word ending with "..."
How this can be done, i have heard that it can be done through RSS.
Can somebody help me?

To accomplish this you need to read the RSS of the blog, from RSS you need to read the Title and the description, after reading the whole description and title you need to trim the description to your desired number of letters. After that you need to check weather the description last word has been completed or not and then you need to remove a the last word if not completed and put the "...".
First we will make a script to trim the description and to put "..." in last:-
<?php
global $text, $maxchar, $end;
function substrwords($text, $maxchar, $end='...') {
if (strlen($text) > $maxchar || $text == '') {
$words = preg_split('/\s/', $text);
$output = '';
$i = 0;
while (1) {
$length = strlen($output)+strlen($words[$i]);
if ($length > $maxchar) {
break;
}
else {
$output .= " " . $words[$i];
++$i;
}
}
$output .= $end;
}
else {
$output = $text;
}
return $output;
}
Now we will define the variables in which we store the values:-
$xml=("http://your-blog-path/rss/");
global $item_title, $item_link, $item_description;
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);
$x=$xmlDoc->getElementsByTagName('item');
Now, we will make an array and store values in it. I am only taking 3 because you have asked it the way. You can change it to anything (The number of post you want to show, put that in the loop)
for ($i=0; $i<3; $i++)
{
$item_title[$i] = $x->item($i)->getElementsByTagName('title')->item(0)->childNodes->item(0)->nodeValue;
$item_link[$i] = $x->item($i)->getElementsByTagName('link')->item(0)->childNodes->item(0)->nodeValue;
$item_description[$i] = $x->item($i)->getElementsByTagName('description')->item(0)->childNodes->item(0)->nodeValue;
}
?>
Now echo all these values, Link is the value where your user will click and he will be taken to your blog:-
FIRST RECENT POST:
<?php echo $item_title[0]; ?>
<?php echo substrwords($item_description[0],70); ?>
SECOND RECENT POST:
<?php echo $item_title[1]; ?>
<?php echo substrwords($item_description[1],70); ?>
THIRD RECENT POST:
<?php echo $item_title[2]; ?>
<?php echo substrwords($item_description[2],70); ?>
Hope this can solve your problem. By the way Nice question.

Click here for the original documentation on displaying RSS feeds with PHP.
Django Anonymous's substrwords function is being used to trim the description and to insert the ... at the end of the description if the it passes the $maxchar value.
Full Code:
blog.php
<?php
global $text, $maxchar, $end;
function substrwords($text, $maxchar, $end='...') {
if (strlen($text) > $maxchar || $text == '') {
$words = preg_split('/\s/', $text);
$output = '';
$i = 0;
while (1) {
$length = strlen($output)+strlen($words[$i]);
if ($length > $maxchar) {
break;
} else {
$output .= " " . $words[$i];
++$i;
}
}
$output .= $end;
} else {
$output = $text;
}
return $output;
}
$rss = new DOMDocument();
$rss->load('http://wordpress.org/news/feed/'); // <-- Change feed to your site
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 3; // <-- Change the number of posts shown
for ($x=0; $x<$limit; $x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$link = $feed[$x]['link'];
$description = $feed[$x]['desc'];
$description = substrwords($description, 100);
$date = date('l F d, Y', strtotime($feed[$x]['date']));
echo '<p><strong>'.$title.'</strong><br />';
echo '<small><em>Posted on '.$date.'</em></small></p>';
echo '<p>'.$description.'</p>';
}
?>
You can easily put this in a separate PHP file (blog.php) and call it inside your actual page.
Example:
social.php
<h3>Latest blog post:</h3>
<?php require 'blog.php' ?>
Also, this code is plug-n-play friendly.

Why not use the Wordpress REST API to retrieve posts -
API URL is : https://public-api.wordpress.com/rest/v1/sites/$site/posts/
where $site is the site id of your wordpress blog
or else simply use this plugin -
http://www.codehandling.com/2013/07/wordpress-feeds-on-your-website-with.html

Related

How to Display A Line of Text if WordPress Category is empty?

I am trying to display a line of text if a specific category (in this case: advisories) is empty, but the code I am trying to use does not display anything.
<?php
if ( in_category( 'advisories' )->count > 0 ) {
echo test;
}
?>
Try this one,
Solution
$custom_terms = get_terms();
foreach ($custom_terms as $term) {
if ($term->count != 0 && $term->name == "Uncategorized") {
echo $term->name . " - blank" . '<br>';
}
}
Screenshot
Hope this will helps you.
For more example, please visit
get_terms Wordpress
WordPress to test for an empty term or category
You can try this one
$category = get_category($id);
$count = $category->category_count;
if( $count > $something ) {
// stuff
}

remove html from the titles of Post and Page Columns of wordpress dashboard

I would like to remove HTML from the titles of Post and Page Columns of wordpress dashboard as in the image attached.
Normally wordpress wont have html tags in the title.But as part of a plugin creation i need to remove these htmls tags .I am trying to create a Tynimce editor to the title fields
Any suggestions?
Well, that HTML is right in your title-field.
Why is it there? It´s absolutely not the right place for markup.
// Replace your Title Column with the Existing one //
function replace_title_column($columns) {
$new = array();
foreach($columns as $key => $title) {
if ($key=='title')
$new['new-title'] = __(Title); // Our New column Name
$new[$key] = $title;
}
unset($new['title']);
return $new;
}
// Replace the title with your custom title
function replace_title_products($column_name, $post_ID) {
if ($column_name == 'new-title') {
$cont = get_the_title();
$cont = str_replace('<', '<', $cont);
$cont = str_replace('>', '>', $cont);
$cont = str_replace('"', '"', $cont); ?>
<a class="row-title" href="<?php echo esc_url( home_url( '/' ) ); ?>wp-admin/post.php?post=<?php echo $post_ID; ?>&action=edit"><?php echo strip_tags($cont); ?></a>
<?php
}
}
add_filter('manage_posts_columns', 'replace_title_column');
add_action('manage_posts_custom_column', 'replace_title_products', 10, 2);
add_filter('manage_pages_columns', 'replace_title_column');
add_action('manage_pages_custom_column', 'replace_title_products', 10, 2);

Wordpress nextpage display Previous 2 of 10 Next

I'm using wp_link_pages() to split my post into multiple pages. I want to achieve something like this as shown in the image below. Instead of showing all the page numbers with links, I want it to show only this format (Current Page of Total Page). Please help me with the exact codes. Thank you so much in advance.
PS: I don't want to use plugins.
There is a simple solution to this problem. I've got this inspiration from source file where function wp_link_pages is defined.
function page_pagination( $echo = 1 )
{
global $page, $numpages, $multipage, $more;
if( $multipage ) { //probably you should add && $more to this condition.
$next_text = "next";
$prev_text = "prev";
if( $page < $numpages ) {
$next = _wp_link_page( $i = $page + 1 );
$next_link = $next . $next_text . "</a>";
}
if( $i = ( $page - 1 ) ) {
$prev = _wp_link_page( $i );
$prev_link = $prev . $prev_text . "</a>";
}
$output =
"<div class=\"prev-next-page\">"
. $prev_link
. "<span class=\"page-counter\">{$page} of {$numpages}</span>"
. $next_link
. "</div>";
}
if( $echo ){
echo $output;
}
return $output;
}
If you need more freedom you can always adapt this function to suit your purposes. Include function into wordpress loop! Like this for example:
if ( have_posts( ) ) {
while ( have_posts( ) ) {
the_post( );
//rest of code
the_content();
page_pagination();
}
}
As you can see, there is "private" function _wp_link_page used to solve your problem. I don't like using "private" functions, but it solves our problem.

How to show recent post in the main domain from subdomain blog

need to show the recent post from my subdomain to my main domain frontend. I am using below code, but its picking only main domain recent post. any help to fetch subdomain recent post ?
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul>
EDIT 2:
So it turns out, that you are not running both sites from the same WordPress installation(otherwise referred to as a WordPress Network). Here is what I can suggest that you use in this case.
Put this code in the main site's functions.php:
/**
* this function retrieves the requested part of the main site
* ok, well basically can be from any site, depending on the $url param, as long as it has the proper function that will display the requested content
* #param $url - the url of the site
* #param $key - part of the name of the function that will display the content
* #param $add_qs - any additional query string that will be appended, use "&params=param1,param2,param3" to pass "param1", "param2" and "param3"
* to the loading function
*/
function get_main_site_part($url, $key, $add_qs = '') {
// cache the result, so we don't make a request with each page load
$cache = ABSPATH . 'wp-content/uploads/main_site_' . $key . '.txt';
$cache_lifetime = 300;
// just to make sure - try to remove the trailing slash in the $url
$url = untrailingslashit($url);
$uri = $url . '/?including_template_part=1&load_part=' . $key . $add_qs;
# reload the cache on every 5 minutes
if (!file_exists($cache) || time() - filemtime($cache) > $cache_lifetime) {
$main_site_html = wp_remote_get($uri);
if (is_a($main_site_html, 'WP_Error')) {
//print_r($main_site_html);
//exit('error! ');
return;
}
$fp = fopen($cache, 'w');
fwrite($fp, $main_site_html);
fclose($fp);
} else {
$main_site_html = file_get_contents($cache);
}
return $main_site_html;
}
Now put this function in your sub-domain's functions.php:
/* HTML LOADING HOOK - For loading content from one site to another - best application in multisite */
function print_requested_template_part() {
// Respond only to requests from the same address...
if ( $_SERVER['REMOTE_ADDR'] == $_SERVER['SERVER_ADDR'] && $_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['including_template_part']) && isset($_GET['load_part']) && $_GET['load_part'] != '' ) {
$part = $_GET['load_part'];
$func = 'render_' . str_replace('-', '_', $part); // if you have declared a function called "render_footer_include", then "?load_part=footer_include"
if ( function_exists($func) ) {
// Allow for passing parameters to the function
if ( isset($_GET['params']) ) {
$params = $_GET['params'];
$params = ( strpos($params, ',') !== false )? explode(',', $params) : array($params);
call_user_func_array($func, $params);
} else {
call_user_func($func);
}
}
exit; // if we don't exit here, a whole page will be printed => bad! it's better to have empty footer than a footer with the whole main site...
}
}
add_action('init', 'print_requested_template_part', 1);
function render_my_recent_posts( $numberposts = 5 ) { ?>
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ) {
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul><?php
}
Then in your main site call this function, where you want your recent posts to appear:
echo get_main_site_part( 'http://questions.admissiontimes.com/', 'my_recent_posts', '&params=5' )
EDIT 1:
Using the sample code that you have in your question, combined with my solution from below, here is what the final code will look like:
<?php
switch_to_blog( 2 ); // Switch to the blog that you want to pull posts from. You can see the ID when you edit a site through the Network Admin - the URL will look something like "http://example.com/wp-admin/network/site-info.php?id=2" - you need the value of "id", in this case "2" ?>
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ) {
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul>
<?php restore_current_blog(); // Restore the current blog ?>
Now, you just put that code wherever you had your original code and everything should be working properly.
You need to switch to the blog in question, using the switch_to_blog($blog_id) function, where $blog_id is the ID of the blog(sub-site) in question.
Then do your normal get_posts/or equivalent/ function and display/store the posts in the way you want.
Once you're done with that, just call restore_current_blog() and that's it.

how to remove read more when full text is on in wordpress?

the code looks like this
function new_excerpt_length($length) {
return 100;
}
add_filter('excerpt_length', 'new_excerpt_length');
there is an option in wp-admin>settings>reading>For each article in a feed, show
if this is set to full text
the excerpt() must return full length article instead of specified length.
how to do this?
Good question! The answer is simple: write your own function!
Open up functions.php in your favorite editor and mash random buttons on your keyboard until you get something like this:
function my_awesome_excerpt ($post_id = false, $full = false, $length = 22) {
if (!$post_id) global $post;
else $post = get_post($post_id);
$text = $post->post_content;
if ($full) return $text;
else {
$text_array = explode(' ', $text);
$return_string = array();
for ($i = 0; $i <= $length; $i++)
array_push($return_string, $text_array[$i]);
$new_awesome_string = '<p>';
$new_awesome_string .= implode(' ', $return_string);
$new_awesome_string .= '</p><p class="readmore">';
$new_awesome_string .= '<a href="' . get_permalink($post_id) . '">';
$new_awesome_string .= 'Read More' . '</a></p>';
return $new_awesome_string;
}
}
Now, you're ready for the cool part. Once you're in your loop, you can write out some magic like this:
echo my_awesome_excerpt();
and it will automagically spit out an excerpt. It's using the global post variable and everything! You can even use it outside of the loop:
echo my_awesome_excerpt($cpt->ID, 22);
and set your own special length!
Or maybe you just know in your heart that it's not worth it, you just want to show the whole thing. How's that look?
Inside the loop, you're going to have to give it a post ID, sorry about that.
echo my_awesome_script($post->ID, false);
I hope this helps. Have a great day!

Resources