How to: WordPress Count Words in a Post

Here is sample code I use to count words in a post ( I found it somewhere while searching something else). Put the code in functions.php (no need to write plugin)

function blog_post_wordcount() {
        global $page, $pages;
        if ( !function_exists('str_word_count') ) {
                return str_word_count(strip_tags($pages[$page-1]));
        } else {
                return count(explode(" ",strip_tags($pages[$page-1])));
        }
}

You can call blog_post_wordcount() from template. Following code will display ad only if a post has more than 100 words:

$words=blog_post_wordcount();
if ( $words >= 100 ) { show_ad(): }

Combine Two WordPress RSS feed into a single Feed

If you have two blogs installed on same domain, you may want to combine two blogs feed into one blog feed. It will provide few benefits:

a) Ease of feed management

b) More readers

c) Better feed stats and much more

Required tools

=> MagpieRSS rss parser for php (download link)

=> FeedCreator lets you easily create RSS 0.91, 1.0 or 2.0, ATOM 0.3 and OPML 1.0 feeds with PHP (download link).

Download required tools

Download required tools to your desktop and upload to your server in myfeed directory using ftp / sftp client. Following instructions assumes that you have a shell access to server:
mkdir myfeed
cd myfeed
wget http://internap.dl.sourceforge.net/sourceforge/magpierss/magpierss-0.72.tar.gz
tar -zxvf magpierss-0.72.tar.gz
cp magpierss-0.72/*.inc .
mv magpierss-0.72/extlib/ .
rm -rf magpierss-0.72*
wget http://www.bitfolge.de/download/feedcreator_172.zip
unzip feedcreator_172.zip
rm *.zip *.txt

Create rss.php script

Now you have all required tools, just create rss.php script :

<?php
$TMP_ROOT = "/tmp";
$DOMAIN_NAME = "http://theos.in/";
$SITE_TITLE = "Your Site / blog Title";
$SITE_DESRIPTION = "Your Site / blog Description";
$SITE_AUTHOR = "Vivek";
$SITE_LOG_URL = $DOMAIN_NAME."logo.jpg";
$RSS_DIR = "/home/lighttpd/theos.in/http";
 
define('MAGPIE_DIR', $RSS_DIR.'/myfeed/');
define('MAGPIE_CACHE_DIR', $TMP_ROOT.'/rsscache');
 
/* include required files */
@require_once(MAGPIE_DIR.'rss_fetch.inc');
@include(MAGPIE_DIR.'feedcreator.class.php');
 
/* Set RSS properties */
$rss = new UniversalFeedCreator();
$rss->useCached();
$rss->title = $SITE_TITLE;
$rss->description = $SITE_DESRIPTION;
$rss->link = $DOMAIN_NAME;
$rss->syndicationURL = $DOMAIN_NAME."/rss/rss.php";
 
/* Set Image properties */
$image = new FeedImage();
$image->title = $SITE_TITLE. " Logo";
$image->url = $SITE_LOG_URL;
$image->link = $DOMAIN_NAME;
$image->description = "Feed provided by ". $SITE_TITLE. ". Click to visit.";
$rss->image = $image;
 
/**************************************************************
showSummery() - Fetch and build new feed
$url = Feed url
$num = Show the most recent posts (default = 10 )
$showfullfeed = true or false, for each article, show full text or summary (default false / summary text)
***************************************************************/
function showSummery($url,$num=10,$showfullfeed=false){
global $rss, $DOMAIN_NAME, $SITE_AUTHOR, $SITE_TITLE;
$num_items = $num;
@$rss1 = fetch_rss( $url );
if ( $rss1 )
{
        $items = array_slice($rss1->items, 0, $num_items);
        foreach ($items as $item)
        {
                $href = $item['link'];
                $title = $item['title'];
                if ( ! $showfullfeed ) {
                        $desc = $item['description'];
                }else{
                        $desc =  $item['content']['encoded'];
                }
                $desc .=  '<p>Copyright &copy; <a href="'.$DOMAIN_NAME.'">'.$SITE_TITLE.'</a>.  All Rights Reserved.</p>';
                $pdate = $item['pubdate'];
                $item = new FeedItem();
                $item->title = $title;
                $item->link = $href;
                $item->description = $desc;
                $item->date = $pdate;
                $item->source = $DOMAIN_NAME;
                $item->author = $SITE_AUTHOR;
                $rss->addItem($item);
        }
}
else
{
   echo "Error: Cannot fetch feed url - ".$url;
}
} // end showSummery()
//***************************************************************/
// Add your feed below:
// showSummery("http://path-to/url/feed",number-of-rss-items,false)
//****************************************************************/
showSummery("http://theos.in/feed/");
showSummery("https://www.cyberciti.biz/tips/feed/");
showSummery("https://www.cyberciti.biz/faq/feed/",5,false);
 
// get your news items from other feed and display back
$rss->saveFeed("RSS1.0", $TMP_ROOT."/rsscache/feed.xml");
?>

Customize script

Set temporary directory to cache rss feed, web server must be able to write to this directory.
$TMP_ROOT = "/tmp";
Set path to rss directory:
$RSS_DIR = "/home/lighttpd/theos.in/http";
Set your domain name, site title, description and author name:
$DOMAIN_NAME = "http://theos.in/";
$SITE_TITLE = "Your Site / blog Title";
$SITE_DESRIPTION = "Your Site / blog Description";
$SITE_AUTHOR = "Vivek";

Finally, set logo file name (replace logo.jpg with actual logo file name):
$SITE_LOG_URL = $DOMAIN_NAME."logo.jpg";

showSummery() function

showSummery($url,$num=10,$showfullfeed=false) fetch remote feed url and build new feed. It accept following arguments:

  • $url = Feed url
  • $num = Show the most recent posts (default = 10 )
  • $showfullfeed = true or false, for each article, show full text or summary (default false )

To combine two RSS feed http://theos.in/blog1/feed/ and http://theos.in/blog2/feed/, call showSummery():
showSummery("http://theos.in/blog1/feed/");
showSummery("http://theos.in/blog2/feed/");
showSummery("http://other-my-blog.com/feed/",5,true); // full feed

Test it

Open a web browser and type url http://your-domain.com/myfeed/rss.php

Download all files and required tools

=> You can download rss.php and required tools here (all GPL licensed except FeedCreator which is under LGPL)

Other tools – Yahoo Pipes

You can use 3rd party service such as Yahoo Pipes, which is an interactive feed aggregator and manipulator. Personally, I like to keep more control on my feed, hence I wrote this script.

How to create Functions that Take a variable number of arguments in PHP

Recently I was coding small application in PHP. I wrote simple function that generates the HTML code of table. Here is what I did first

startTable($col, $heading1, $heading2);

Problem with above function was clear I needed something which can very both column and heading without writing 2-3 functions. I know this can be done in ‘C’. So I opened the PHP documentation and I come across this “PHP 4 has support for variable-length argument lists in user-defined functions. This is really quite easy, using the func_num_args(), func_get_arg(), and func_get_args() functions.” :)

So I rewrote my startTable() as follows:


function startTable($allArgs){
	// the number of arguments passed to the function
	$size = func_num_args();

	echo '<table border=1 width=100%><tr>';
	$width=100;
	if ( $size == 2 ) $width=50;

	if ( $size == 3 ) $width=33;

	if ( $size == 4 ) $width=25;

        // iterate through the arguments and add up the numbers
	for ($i = 0; $i < $size; $i++) {

		$colTitle = func_get_arg($i);
		echo "<td width=$width% align=center bgcolor=#BFBFBF>$colTitle</td>";

	}
	echo "</tr>";
}

Basically func_num_args() returns the number of arguments passed to the function and func_get_arg($i) return an item from the argument list. Finally I endup creating addRow as follows:


function addRow($data){

	$size= func_num_args();
	$width=100;
	if ( $size == 2 ) $width=50;

	if ( $size == 3 ) $width=33;

	if ( $size == 4 ) $width=25;

	echo "<tr>";
	for ($i = 0; $i < $size; $i++) {

		$align="";
		$colData = func_get_arg($i);

		$tmp=split("\|","$colData");
		$align = current($tmp);

		$text =  end($tmp);
		if ($align == $text ) $align="left";

		echo "<td width=$width% align=$align>$text</td>";
	}
	echo "</tr>";

}
?>

How to call perl or php script from HTML file?

Easiest way to do this is call php/perl script as javascript. Since javascript is client side stuff, php or perl script need to writeback output using javascript commands only. This is useful if you have lots of HTML files and would like to do some server side processing. For example Tips & Tricks section on our site has lots of html pages which uses code as follows:

<script language="JavaScript" type="text/javascript" src="http://rss.cyberciti.biz/rss2html.php?u=http://blogs.cyberciti.biz/feed/">
<script>

Above code generates recent post posted in blogs.cyberciti.biz/hm blog. Main advantage of this technique is simple, you can use it from HTML file and your javacode is also hidden (although other better ways exists to do this).

(A) An example of PERL, create file called html.pl as follows and put into your cgi-bin directory:

#!/usr/bin/perl
use strict;
use warnings;
use CGI;
my $q = CGI->new();
my $info = "Server: ". $ENV{'SERVER_NAME'} . "
Script name: ". $ENV{'SCRIPT_NAME'}; # need to send header otherwise sky will fall on you print $q->header(); # always get back to user after perl code print "document.write('Hello world
I am called from HTML page $ENV{'HTTP_REFERER'}
');"; print "document.write('$info');";

Add following line to your HTML code (replace mydomain.com with your real domain name):

<script language="JavaScript" type="text/javascript" 
src="http://www.mydomain.com/cgi-bin/html.pl"
<script>

(B) An example of PHP, create file called html.php as follows and put into your webserver directory:

<?php
 $ref = $_SERVER['HTTP_REFERER'];
 $ser = "Server: ". $_SERVER['SERVER_NAME'] .  "
Script name: ". $_SERVER['SCRIPT_NAME']; echo "document.write('Hello World
I am php code called from HTML file:' );"; echo "document.write('$ref
');"; echo "document.write('$ser');"; ?>

Add following line to your HTML code (replace mydomain.com with your real domain name):

<script language="JavaScript" type="text/javascript" 
src="http://www.mydomain.com/html.php"
<script>

PHP code is bit easier to use as compare to PERL.