Dec 19, 2011

How To Show Latest Tweets Using PHP JQuery

Today I am sharing my newly PHP and JQuery coded snippet which is going to display your latest tweets in a fade in and fade out effect using Twitter timeline RSS feeds.

Here is the PHP function to get the tweets:

function latest_tweets(){
//global $post;
$doc = new DOMDocument();
$feed = "$meta.rss";

$outer = '<ul id="tweets">';
$max_tweets = 15;
$i = 1;
foreach ($doc->getElementsByTagName('item') as $node) {
$tweet = $node->getElementsByTagName('title')->item(0)->nodeValue;
//if you want to remove the userid before the tweets then uncomment the next line.
//$tweet = substr($tweet, stripos($tweet, ':') + 1);
$tweet = preg_replace('@(https?://([-w.]+)+(:d+)?(/([w/_.]*(?S+)?)?)?)@',
'<a href="$1">$1</a>', $tweet);
$tweet = preg_replace("/@([0-9a-zA-Z]+)/",
"<a href="$1">@$1</a>",

$outer .= "<li>". $tweet . "</li>n";

if($i++ >= $max_tweets) break;
$outer .= "</ul>n";
return "<div class='post'><p><b>Latest Tweets </b>".$outer."</div>";
echo latest_tweets();

In the above function we are fetching the RSS feed from the twitter timeline. Then we finally break it into segments and display it using the loop method.

Now we have to display the tweets with jquery effect.

So here is the jquery function to display the tweets in a fadeIn effect.

<script type="text/javascript">
function tweetRender( prospectID )
prospectID.delay() .fadeIn() .delay(2000).fadeOut(
if( > 0)
{tweetRender( );}
{tweetRender( prospectID.siblings(':first'));}


$('#tweets li').hide();
tweetRender( $('#tweets li:first') );


In this tutorial we are using basic PHP and JQuery to display the tweets. You can download it and check the Demo.

Dec 17, 2011

JQuery Page Loading Popup

In a website whenever a user clicks a link, that user has to wait for seconds to see the new loaded page. In today’s tutorial we will show an interesting popup after the click event occurs and after few seconds the page will load.

This is just an interactive way to load a page; it will take the same time to load as it was before.

The basic HTML Code:
<div style="display: none;" id="overlay"></div>
<div style="display: none;" id="popup">
<img src="loading.gif" />

<a href="" id="link">Click Here</a>

The JQuery code:

<script type="text/javascript">
jQuery("#link").click(function(event) {
event.preventDefault(); //to stop the default loading
var a_href = $('#link').attr('href'); // getting the a href link
jQuery("#overlay").css('display','block'); // displaying the overlay
jQuery("#popup").css('display','block'); // displaying the popup
jQuery("#popup").fadeIn(500); // Displaying popup with fade in animation
setTimeout(function() {
jQuery("#popup").fadeIn(4000); //function to redirect the page after few seconds
window.location.replace("http://"+a_href); // the link
}, 3000);

Try the Demo, and suggestions are always open.

Dec 14, 2011

Photoshop CS5 Menu for Websites

This tutorial helps you to make or design a horizontal navigation bar with your desired color combinations. In this tutorial I have used the color combination Blue background with Gray buttons as it provides a decent and good gradient effect to observe.

 Our Tutorials Begins From Here:

This is a preview of the result that we are going to get after completing the tutorial.

Result Preview

Step 1: At first we are going to create a new document and fill some colors in it.

  • Open Photoshop go to ‘File’ click ‘New’ add your desired name and size like I choose a size of 600 by 250 pixels.

  • After creating the document fill the background color with your desired color (which I have choose blue).

  • To fill the desired color, go to Edit > Fill > Use (or just press Shift+F5). Select a color from the use tab as I choose “Blue” and click it in the background area.

You would get result like this,

Result of Step 1 Result

Step 2: Now we are going to make the background for the navigation bar inside which the buttons or tabs are placed.

  • To create a new layer, go to Layer > New > Layer (or press Ctrl+ Shift+ N).

  • Select the layer and select the Rounded Rectangle Tool (or press U twice).

  • Adjust the size of the rectangle by selecting the “Fixed Size” from the Geometric Options’ button in the Rectangle Panel appeared under Menu Panel.

  • Select the size you desire, like I choose 500 by 60 pixels.

  • You can adjust the radius of the corners too in the same panel.

  • After setting the sizes click at the desired area you want to draw the navigation bar.

You would get result like this,

  • Result of Step 2Select the navigation layer from the layers list and click on the button at the bottom which has a circle in a rectangular box showing “Add Mask Layer”.

This will divide the layer into mask objects so that you can fill a particular color into the navigation bar only without tempering the background layer.

  • Fill the navigation bar with a single color or add a gradient effect using linear effect with multiple colors.

  • Rasterizing the layer of the navigation layer you would get the single form layer to add other layer options to it.

After completing the above step you would get a result like this,

Result of Step 2 (Part 2)

Step 3: Now we are going to add some layer styles to the navigation bar on its background.

  • To open layer styles go to Layer > Layer Style (or select the layer, right click on it and select “Blending Options” in it) and select Outer Glow from it.

  • Make glowing changes accordingly to your desired design (or just follow the given below picture details).

  • To add some more layers select any options and add your desired changes to the navigation bar.

Result of Step 3

Result of Step 3 (Part 2)

Step 4: Now we are going to make buttons in the navigation bar.

  • Create a new layer by following Step 2.

  • Select the rounded rectangle tool and set your desired size like 150 by 50 pixels and draw maximum no. of buttons which can be drawn.

  • Use the ‘Add Mask Layer’ and select the first layer add you’re desired layer option from the list in blending options.

  • You can add changes in color and change gradient effects by clicking the gradient tab in the “Gradient Overlay” tool and get the below result.

Result of Step 4You will get the result as,

Result of Step 4 (Part 2)

Step 5: Now we are going to add text to the buttons.

  • To add text to the buttons create a new document for every new button, it helps in adjusting the position of the text in the button later.

  • Select the desired font, size and style from the text bar under the Menu bar.

  • Select the color from the color window on the right side of the desktop.

  • Write your text in the button like “Home” and then adjust the position of the text using ‘Move’ tool.

Your result should look similar to this,

Result of Step 5

Step 6: Now in the last we are going to highlight the button to shown it is in selection or the mouse is on it.

  • Select any button to highlight it, so that we a mouse comes on it or when it is in selection then the color of the button change to shown it is distinguished from other.

  • Select the color from the color window for the button and fill the color in the button with the Fill (or Paint Bucket) tool.

  • Add some outer glow from the Blending option form Step 3 and center the glow on the highlighted button. You can use the following setting in the picture,

Result of Step 6After applying the above changes your final result should look like this,

This is the final result you would get after completing this tutorial.

Dec 9, 2011

How to get your drupal questions answered in an IRC Channel

Would you like your drupal questions answered by community experts? Then read this post - it'll tell you the best way to get answers.

Firstly, if you really want good answers, learn how to ask good questions. I thought I knew how to ask good tech-related questions until I read this: Then I realised that I did know how to ask good questions, and now I knew how to ask much better questions. That's helped me on irc and on support forums. You basically want to ask your question like this:

"I'm trying to achieve [A]. I thought the best way to do this was to [B]. I read the documentation and it said to do [X]. I did it, I expected to see [Y] but actually saw [Z]. What am I doing wrong?"

Out there some drupal genius (like me! lol) reads this question. And immediately knows a few things:

The outcome that you're trying to achieve. Knowing this, we may have a better suggestion instead of [B] and thereby solve your problem.

You're already thinking - because of [B]. Whohoo! We know that you're someone who is thinking how to do something which will achieve your outcome. Tech geniuses would rather answer questions from people who are willing to do their own thinking.

You read documentation - double points. It means you're not asking someone else to do all the hard work. Plus you're learning new stuff. Both good pointers, and you're more likely to get helped.

When you did [X] you've told us what you expected to see when you tried [X]. That means you're thinking. Then you say that instead of [Y] you saw something else - [Z]. Awesome - that's valuable information.

Questions like, "Help, my website is broken!" or "Views isn't working" or "Taxonomy isn't linking properly" will get you ignored almost 100% of the time.

Read the documentation. Yes, RTFM applies - always. There's a reason documentation is written - and if it's out of date, update it yourself!

Maybe someone else has already asked your question. Search via google (go to and type " terms related to your problem"). If nothing shows up, search the internet. If nothing shows up, time to ask your question!

Ask your question in the right channels, those would be the forums on or the issue queue for the module you're having a problem with.

Or simply figure out how to join #drupal on IRC (for that you can use its simple and easy too use and compatible with any browser, since I'm using it ;) ), you can also choose your preferable channel from here or

Remember the BOT named 'Drupalicon' is there for you, if you wanna learn how to interrogate with 'Drupalicon' on IRC read this, if in case you're finding it difficult just type a message in the Drupal channel 'bot?' (without quotes) there will be a reply 'I'M UP! I'M UP!'.

Please don't ask your question in because this is for location-specific activities, and there may be other people on who'd also like to know the answer to your question (plus, your question on the drupal forums is searchable, so in a month someone else may have the same problem you're having and also wants to know the solution - be kind and place your question somewhere they can find it!).

If you're going to post a question in the issue queue, first read the Troubleshooting FAQ. If you're having a problem with your Drupal site, you're almost certainly not alone. Your questions may already have been asked and answered many times. Save yourself some time and start with this list of Frequently Asked Questions (FAQs) before you post an issue in the queue.

Don't be a support leech. Play nicely! And learn how to be part of a community, particularly a self-organising one.

Lastly, read this post and follow all of this advice! It will transform you into the kind of person whom other people enjoy helping, and take you one step closer to being Certified to Rock! And if someone does something which violates any of these guidelines, gently point them to this post.

JQuery Popup | JQuery Slide Popup

Now a day’s JQuery’s are used almost in all websites. In today’s tutorial I am going to share a new way to show a pop up message. Everyone is getting bored with typical fade in fade out pop up messages. So let’s make it interesting with a pinch of jquery and css.

In this tutorial we are going to make two javascript functions which will be used to slide in and slide out a div.

function openOffersDialog() {
$('#overlay').fadeIn('fast', function() {

function closeOffersDialog(prospectElementID) {
$(function($) {
$(document).ready(function() {
$('#' + prospectElementID).css('position','absolute');
$('#' + prospectElementID).animate({'left':'-100%'}, 500, function() {
$('#' + prospectElementID).css('position','fixed');
$('#' + prospectElementID).css('left','100%');

In the first function we are making a call to a div to fadeIn and in that fade in function we are sliding our popup from right to left.

The next function is used to slide the function from center of the screen to the extreme left side so it appears us to be disappeared. In this function we also set the overlay div to fadeout.

So let’s construct with our HTML part.

<body onload="openOffersDialog();">
<div id="wrapper">
<div id="overlay" class="overlay"></div>
<a onclick="openOffersDialog();">Click Here To See The PopUp</a>
<div id="boxpopup" class="box">
<a onclick="closeOffersDialog('boxpopup');" class="boxclose"></a>
<div id="content">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum.

This was a small tutorial on sliding a popup without using any JQuery UI and making it different from other popups.



Dec 7, 2011

Is Drupal 7 slow?

There are some performance issues with Drupal 7 currently on some server/server configurations.

As a start, you could try the 7.x-dev snapshot to see if there are any improvements.

  • Is your server is a shared hosting or your own server or local development environment?
  • Did you already use Drupal 6 in the same environment?
  • Did you enable the basic performance settings, like aggregating CSS/JS?
  • To do anything more, you will actually need to figure out what exactly is slow, there is often a specific bottleneck that is slowing down the whole site. As a start, you could enable devel.module and the query logging to see if there are any slow queries on that page.
  • If this is your own server, I strongly suggest to install and enable APC.

Most probably, you are hitting Avoid re-scanning module directory when multiple modules are missing. It happens if you have some missing modules in your installation.

Try to check your system table:

[php]SELECT name, filename FROM system WHERE type = 'module' AND status = 1 ORDER BY filename[/php]

And clean-up any modules that are still enabled but missing from the filesystem.

Overall, Drupal 7 is way more resource friendly and scalable then Drupal 6, other then some unfortunate regressions like this one.

Drupal 7 is optimized out of the box for large website featuring advanced cache features, reverse proxy, load balancer. You would say that this would make drupal 6 too fly, but there is noticable difference between drupal 6 and drupal 7 performace with same high end server setup.

Drupal 7 may let you down initially, but given the proper hardware and software environment, you can do wonders with drupal in terms of speed.

Drupal 7 uses too many files and like D6, it uses also too many SQL queries (in comparison with other CMS). So the first hit could take time, especially when you have a slow disk and files are not in OS cache.

In a normal situation, when cache is available, everything should be ok. There are many layer of cache: OS cache to avoid reading PHP files, opcode cache (like APC, not enabled by default) to avoid re-parsing PHP files, MySQL cache to avoid re-execute queries multiple times.

Morally, most of the time its not drupal, its probably the server at fault. Its true over the time drupal has evolved to be a resource hungry. But its only till you precise it that way. The fact is that drupal 7 is infact very resource friendly, since when it is used on a VPS with MemCache, APC installed then it flew like anything.

Learn PHP | PHP Tutorials | PHP Lessons | Part 2

So welcome back to part 2 of the PHP tutorial. If you are new to PHP then I would recommend you to first check the Part 1


  • Within this lesson you will learn how to assign values to variables in PHP and use them in some expression.

  • The topics covered are :

  1. Understanding Variables.

  2. Data Types.

Let’s get started right away…..

Understanding Variables

  • Variables

    • Variables are containers in which values can be stored and later retrieved.

    • They are basically the building blocks of any programming language.

For eg :- you can have a variable called “$number” that holds the value the value  “5

[php]$number = 5;[/php]


$name that holds the value “bruce

[php]$name = "bruce";[/php]

Note :-        In PHP a variable will always be prefixed with a “$” symbol. If you can remember that declaring variable will be SUPER-EASY….

  • Just take “=” symbol with variable name on the left and value you want on right.

Here take a look at the example : -

[php]$name = "bruce";
echo "Hello";
echo $name;[/php]


Output produced is : Hello bruce.

  • Above example uses the “echo” command to display the value stored in a variable, in the same way that you would display a fixed piece of text.

  • The more descriptive your variable names are the more easily you will remember what they are used for, when you come back to a script several months later.

  •  Good variable name tells exactly what kind of value you can expect to find and stored in them.

  • Also, Variable name can only contain letters, numbers and underscore character. And each must begin with a letter or a underscore.

  • When the variable is assigned, the value given doesn’t have to be a fixed value

For eg :-

[php]$sum = 16 + 30;[/php]

-      ’16 + 30’ can also be an expression. An expression is where two or more values are combined using an operator to produce a result.

Let’s take a look at this …..

[php]$sum = 16 + 30;
echo $sum;[/php]

-      As seen above the values ‘16’ and ‘30’ are combined using the ‘+’ symbol & result is returned using “echo” command.

  •  Text Strings

    • Text Strings always have to be enclosed in quotation mark(“”) mark, and most of the time it doesn’t make any difference whether you use single(‘’) or double(“”) quotes.

    • But when you are dealing with variables it does make a difference.

Let’s look at an example to be clearer on this.

[php]$name = "bruce";
echo "Hello, $name";[/php]

  • Here the value of the variable is included in the string.

Output produced is : Hello, bruce.

Now look at this example below.

[php]$name = 'bruce';
echo 'Hello, $name';[/php]

  • Here no substitution of any variable takes place and output thrown is

Output produced is : Hello, $name.

  • You can overcome this by using ( ) OR { }

  • So if you want to display weight value with a suffix, your statement might look like this

[php]echo "The total weight is { $weight } lb";[/php]

  • If the braces hadn’t being placed around this particular weight variable , PHP would find a value which doesn’t exist. Like this

[php]echo  "The total weight is $weight lb";[/php]

  • Not to be too confusing but you can also do the same thing by using concatenation operator “.” to join two or more strings together as shown here

[php]echo 'The total weight is ' . $weight . 'lb' ;[/php]

-      The three values here are two fixed string and a variable.

-      If you assign a value to variable i.e $weight = 99 . The statement would produce output like this.

Output produced is : The total weight is 99lb.

Data Types

  • Each variable that holds certain value has a data type that defines what kind of a value it is holding.



BooleanA truth value can be TRUE or FALSE
IntegerA number value, can be a positive / negative whole number
Double (or float)A floating point value can be any decimal number
StringAny alphanumeric value, any ASCII character.

  • When you assign a value to a variable the data type is also set.

  • PHP determine the data type automatically, based on value you assign to the variable.

  • If you need to check what data-type PHP thinks the value is you can use the gettype() function.

[php]$value = 7.2 ;
echo gettype($value);[/php]

  • Running this function, the data-type of a decimal number is double.

  • The complimentary function of gettype() is settype(), which lets you overwrite the data-type of a variable.

For eg:-

[php]$value = "22 January 2010";
settype( $value, "integer");
echo $value;[/php]

  • In this case the string begins with number, but the whole string is not an integer. The conversion converts the first non-numeric character and discards the rest and the output produced is just the number 22.


Output produced is : 22

  • Sometimes PHP will perform an implicit data-type conversion if values are expected to be of a particular type which is known as Type Juggling.

     For eg:-

[php]echo 100 + "10 inches" ;[/php]

-      The addition (+) operator expects to sit between two numbers. String type values are converted to double or integer in this case “10 inches” is treated is “10” before the addition operation is performed so the result is “110

Output produced is : 110

  • The same thing happens when a string operator is used on numeric data.

  • If you perform a string operation on numeric data-type, the numeric value is converted to a string first. We saw this earlier when we used the concatenation “.” operator to display a numeric value.

  • It is possible to use the value stored in a variable as the name of another variable.

-      Again, I know this might sound a bit confusing so let’s look at an example.

[php]$my_age = 21 ;
$varname = "my_age";
echo "the value of $varname is ${ $varname }";[/php]

-      The output produced in this example is

Output produced is : The value of my_age is 21

-      Because the string “my_age” is enclosed in a double quotes the dollar($) sign indicated that a variables value should become a part of string.

-      The construct shown i.e $ { $ varname } indicates that the value of variable should become a part of the string which is known as Variable Variables.

-      The braces around the variable $ { $ varname } is to indicate that it should be referenced first.

-      The next example shows the same output as the last one except that it uses the concatenation operator.

[php]echo 'The value of ’ . $varname . 'is' . $$varname;[/php]

Output produced is : The value of my_age is 21

So here we end our part 2 and I recommend you to go through the entire tutorial once again, and replicate all the examples in your localhost and test it if you are prepared for the 3 part.


Dec 4, 2011

Simple JQuery Toggle Tutorial | CSS JQuery Slide Toggle

Today I am going to share a very common and easy jquery tutorial with you. A JQuery Slide Toggle function.

.slideToggle() function is used to hide or show matched elements in a sliding effect.

So the basic syntax is


So this was the basic syntax on how to slide toggle a div, now lets start with some real working examples.

So first the basic html code:

<div id="toggle">
<li>Youtube Video Scraping</li>
Always I wondered to display youtube videos below my posts or for some other purpose. But always had to use some plugins or some complicated scripts. So finally coded for you people a small function which will fetch or scrape...<a href="">Continue reading</a>
<li>WordPress Multiple Category Search</li>
Since when I started wordpress, I had a question in my mind, why wordpress doesn’t give multiple search option? I googled a lot, but couldn’t find a plugin or code which exactly works. So finally decided to go more into...<a href="">Continue reading</a>

<li>Youtube Video Scraping</li>
Always I wondered to display youtube videos below my posts or for some other purpose. But always had to use some plugins or some complicated scripts. So finally coded for you people a small function which will fetch or scrape...<a href="">Continue reading</a>

<li>Ten WordPress Useful Functions And Snippets</li>
Some useful WordPress PHP funtions. Just copy and paste these functions in your themes functions.php file Change the WP Login Logo & URL Link Load JQuery From Google CDN How to remove the WordPress Version Information Remove Default WordPress Meta...<a href="">Continue reading</a>

<li>A Good PHP Developer Can Answer This | PHP Test</li>
PHP developers go through 3 stages in their life Beginner Good Best A beginner PHP coder is some one who just started making some PHP projects in CMS like WordPress, Joomla, Magento and other PHP based CMS. A good PHP... <a href="">Continue reading</a>


And finally our js

<script type="text/javascript">
$(document).ready(function() {


In our basic html layout, we have placed a div exactly next to our li. So we tell the jquery to slide exactly the next div of the current clicked li. If we directly write slideToggle then it will slide all the div's of the current page. In the above js code, we are also using a stop() function. This is essential to use, to avoid multiple clicks on a same li making it to slide for continuous multiple times of sliding.

Here's a working demo of the above code

Nov 27, 2011

Youtube Video Scraping | Fetch Youtube Video Via RSS

Always I wondered to display youtube videos below my posts or for some other purpose. But always had to use some plugins or some complicated scripts. So finally coded for you people a small function which will fetch or scrape youtube videos through GDATA RSS.

$search = 'linkinpark';//Search Term
$file = file_get_contents(''.$search.'&client=ytapi-youtube-search&v=2');
$rss = new SimpleXMLElement($file);
$limit = '10'; //Videos Limit to display
$ctr = '0';
foreach($rss->entry as $idx => $key)
if($ctr == $limit)
echo '<div id="video">';
echo '<p class="title">'.$key->title.'</p>';
echo '<p class="video">'.$key->content.'</p>';
echo '</div>';

My idea behind getting the videos is first to fetch the entire contents of the GDATA RSS page using file_get_contents

After storing the RSS into a file as a string, we will convert it into proper XML using SimpleXMLElement

We store this XML version into a variable which consists of arrays and objects.

Finally we bring the foreach and break down the array into pieces. Thats it. Go and test it yourself.

This function is the basic version, I am sure you can modify it and make more flexible.


Nov 14, 2011

Wordpress Multiple Category Search

Since when I started wordpress, I had a question in my mind, why wordpress doesn’t give multiple search option? I googled a lot, but couldn’t find a plugin or code which exactly works.

So finally decided to go more into deep of wordpress and php, and came up with a code which works.

Functioning of this code:  Searches all posts using a custom search box where 2 drop-down box will be displayed with values of categories in it.

Have you ever played with search URL? Or tags URL or Categories URL?

Very few might have knowledge that wordpress supports multiple tags or multiple categories. Don’t believe me, in your URL, type this


Now what does this means? Simple when you type tag1+tag2 it will show you posts with having both the tags. And when you type tag1, tag2 it will show you all the posts having either tag in it.

Same works for categories.,cat2

Now I tried this same functionality in search URL of Wordpress.

And woila it worked!!!!

Here “s” is your search term and “cat=114” is your category ID. This will work and display all the posts with the search term only in category ID 114.

But the only problem in this is that it will just take one category at a time.

Wordpress doesn’t supports this URL

Here comes a big problem. After a lot of search I found that “+” is considered as a space in URL. So we need to write a function which will make this space act as a + operator.

add_action( 'parse_request', 'category_search_logic', 11 );
function category_search_logic( $query ) {
if ( ! isset( $query->query_vars[ 'cat' ] ) )
return $query;
// split cat query on a space to get IDs separated by '+' in URL
$cats = explode( ' ', $query->query_vars[ 'cat' ] );
if ( count( $cats ) > 1 ) {
unset( $query->query_vars[ 'cat' ] );
$query->query_vars[ 'category__and' ] = $cats;
return $query;

function check()
$query = str_replace('&cats=', '+', $url);
if(isset($query) && ($query != $url))

add_action('parse_query', 'check');

After getting this function in our functions.php file, the multiple categories URL with search will work.

So it’s time to design a simple search form.

Paste this anywhere in your theme.

<!-- Search Form -->
<div style="margin:10px 0 10px 0;">
<form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<table cellspacing="5">
<label for="s" style="margin:10px;">Search</label>

<input type="text" class="field" name="s" style="width: 100px;"/>
<?php wp_dropdown_categories('show_count=1&hierarchical=1'); ?>
<?php wp_dropdown_categories('show_count=1&hierarchical=1&name=cats'); ?>
<input type="submit" class="submit" name="submit" id="searchsubmit" value="Search" style="display: block; position: relative; top: 7px;"/>
<!-- Search Form -->


That’s it, now just go and try your wordpress site will be having a multiple category search option. No plugin and no hundred lines of code, and best part, it’s fully flexible to use. If you want one more category drop down then just copy paste the category php code one more time.

Nov 8, 2011

Ten Wordpress Useful Functions And Snippets

Some useful Wordpress PHP funtions.

Just copy and paste these functions in your themes functions.php file

Change the WP Login Logo & URL Link

function my_custom_login_logo() {
echo '';
add_action('login_head', 'my_custom_login_logo');

function change_wp_login_url() {
echo bloginfo('url'); // OR ECHO YOUR OWN URL
function change_wp_login_title() {
echo get_option('blogname'); // OR ECHO YOUR OWN ALT TEXT
add_filter('login_headerurl', 'change_wp_login_url');
add_filter('login_headertitle', 'change_wp_login_title');


Load JQuery From Google CDN

// even more smart jquery inclusion :)
add_action( 'init', 'jquery_register' );

// register from google and for footer
function jquery_register() {

if ( !is_admin() ) {

wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', ( '' ), false, null, true );
wp_enqueue_script( 'jquery' );

How to remove the WordPress Version Information

// remove version info from head and feeds
function complete_version_removal() {
return '';
add_filter('the_generator', 'complete_version_removal');


Remove Default Wordpress Meta Boxes

function remove_default_post_screen_metaboxes() {
remove_meta_box( 'postcustom','post','normal' ); // Custom Fields Metabox
remove_meta_box( 'postexcerpt','post','normal' ); // Excerpt Metabox
remove_meta_box( 'commentstatusdiv','post','normal' ); // Comments Metabox
remove_meta_box( 'trackbacksdiv','post','normal' ); // Talkback Metabox
remove_meta_box( 'slugdiv','post','normal' ); // Slug Metabox
remove_meta_box( 'authordiv','post','normal' ); // Author Metabox

function remove_default_page_screen_metaboxes() {
remove_meta_box( 'postcustom','post','normal' ); // Custom Fields Metabox
remove_meta_box( 'postexcerpt','post','normal' ); // Excerpt Metabox
remove_meta_box( 'commentstatusdiv','post','normal' ); // Comments Metabox
remove_meta_box( 'trackbacksdiv','post','normal' ); // Talkback Metabox
remove_meta_box( 'slugdiv','post','normal' ); // Slug Metabox
remove_meta_box( 'authordiv','post','normal' ); // Author Metabox


Include custom post types in the search results of WP

function searchAll( $query ) {
if ( $query->is_search ) { $query->set( 'post_type', array( 'site','plugin', 'theme','person' )); }
return $query;
add_filter( 'the_search_query', 'searchAll' );


Add Excerpt to pages

if ( function_exists('add_post_type_support') )
add_action('init', 'add_page_excerpts');
function add_page_excerpts()
add_post_type_support( 'page', 'excerpt' );


Change the order of Admin Menu

function custom_menu_order($menu_ord) {
if (!$menu_ord) return true;
return array(
'index.php', // this represents the dashboard link
'edit.php?post_type=events', // this is a custom post type menu
'edit.php?post_type=page', // this is the default page menu
'edit.php', // this is the default POST admin menu
add_filter('custom_menu_order', 'custom_menu_order');
add_filter('menu_order', 'custom_menu_order');


Change the length of excerpts

function new_excerpt_length($length) {
return 100;

add_filter('excerpt_length', 'new_excerpt_length');


Enable GZIP output compression

if(extension_loaded("zlib") && (ini_get("output_handler") != "ob_gzhandler"))
add_action('wp', create_function('', '@ob_end_clean();@ini_set("zlib.output_compression", 1);'));


Get the First Image from the Post Content

function getImage($num) {
global $more;
$more = 1;
$link = get_permalink();
$content = get_the_content();
$count = substr_count($content, ' $start = 0;
for($i=1;$i $imgBeg = strpos($content, ' $postOutput = substr($post, 0, $imgEnd+1);
$postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);;
$image[$i] = $postOutput;
if(stristr($image[$num],' $more = 0;


Credit: Users Of

Oct 29, 2011

A Good PHP Developer Can Answer This | PHP Test

PHP developers go through 3 stages in their life

  • Beginner

  • Good

  • Best

A beginner PHP coder is some one who just started making some PHP projects in CMS like Wordpress, Joomla, Magento and other PHP based CMS.

A good PHP coder completed or knows all PHP based CMS and is about to finish PHP Frameworks like Yii, Cake, Symphony, CI and others.

A best PHP coder is a complete package of Beginner and Good, that person needs no questions cause he might be ready with all the answers.

Now its time to rate yourself in PHP, I googled and found some questions which only a Good coder can answer.

A: Its the scope resolution operator (double colon ::). This is valid for PHP 4 and later only.

Q2: What is the cause of this warning: 'Warning: Cannot modify header information - headers already sent', and what is a good practice to prevent it?
A: Reason: body data was sent, causing headers to be sent too. This normally occurs when white space is sent accidentally.

Q3: What's wrong in this query: "SELECT * FROM table WHERE id = $_POST[ 'id' ]"?
A: This is the worst practice to select some row or fetch data, use specific row instead of *. Use PDO prepared statements to avoid SQL Injections.

Q4: What is wrong with this if statement: if( !strpos( $thread, $needle ) ...?
A: strpos returns the index position of needle, it could return false if its at 0 position. Instead give a if else check if( false !== strpos( $thread, $needle )...

Q5: What is the preferred way to write this if statement, and why?
if( 5 == $someVar )
or if( $someVar == 5 )
A: The former, it prevents accidental assignments of 5 to $somevar if you forgot two == signs(if( $someVar = 5 ))

Q6: In the below code, whats the value of $a and $b after the function call and why?

function doSomething( &$arg )
$return = $arg;
$arg += 1;
return $return;

$a = 3;
$b = doSomething( $a );

A: $a is 4 and $b is 3. The former because $arg is passed by reference, the latter because the return value of the function is a copy of (not a reference to) the initial value of the argument.

Q7: What is the difference between public, protected and private in a class definition?
A: public makes a class member available to "everyone", protected makes the class member available to only itself and derived classes, private makes the class member only available to the class itself.

Q8: What is wrong with this code:

class SomeClass
protected $_someMember;

public function __construct()
$this->_someMember = 1;

public static function getSomethingStatic()
return $this->_someMember * 5; // here's the catch


A: Static methods don't have access to $this, because static methods can be executed without instantiating a class.

Q9: What is the difference between an interface and an abstract class?
A: An interface defines a contract between an implementing class is and an object that calls the interface. An abstract class pre-defines certain behaviour for classes that will extend it. To a certain degree this can also be considered a contract, since it garantuees certain methods to exist.

Q10: Which one is correct?: $array[name] or $array['name']?
A: Both of them will output the value, but only the quoted form is correct. To check this define(name,0); and see the bugs flying in the website.

Now how much did you score out of 10, comment your score below, and if you have any more questions then let me know after all sharing is caring ;)

Oct 26, 2011

Insert Record Into Database Using AJAX | How To Insert Data Into Database Using AJAX

In todays tutorial, I am going to teach you, HOW AJAX WORKS. This tutorial is good for people who are seeking on internet to learn AJAX with PHP and MYSQL.

I am going to share a AJAX Driven tutorial with you, in which we will insert a record in our Database through AJAX, which means data will be added into database, without refreshing the page and we will also show the added values.

So lets start this, first we need to setup a folder structure.
Make a folder and inside it, add three files,

  • index.php

  • data.php

  • ajax.gif

Now we will add basic html code into our index.php file


<div id="wrapper">
<input type="text" id="name" value="Your Name" />
<input type="button" value="Submit" onclick="addRecord()" />
<div id="propspectDiv"></div>
<table id="data" border="1" cellspacing="0" cellpadding="0" width="75" style="display:none;"></table>



Now comes the main AJAX code.

Inside your head tag, add the following code:


<script src="" type="text/javascript"></script>
<script type="text/javascript">

function addRecord()
var term_name = $('#name').val();        //Storing the value of textbox into a variable

if(term_name == '')        //Checking for NULL
$('#propspectDiv').html('Enter A Valid Name');    //Prints the progress text into our Progress DIV
$('#name').addClass('error');                    //Adding the error class to the progress DIV
$('#propspectDiv').removeClass('error'); //Removing the error class from the progress DIV
$('#propspectDiv').html('Submitting your Request.<img src="ajax.gif" />');//Prints the progress text into our Progress DIV

url : 'data.php', //Declaration of file, in which we will send the data
"name" : term_name                //we are passing the name value in URL
success : function(data){
$('#propspectDiv').html('Your Name is added to our records'); //Prints the progress text into our Progress DIV
$('#data').css("display","block");  //Changes the style of table from display:none to display:block
$('#data').html(data);                //Prints the data into the table
}, 2000);




In our AJAX function first we are storing the value of textbox in a variable.
Then we check whether the variable is not passed NULLED, if condition is satisfied, then it enters to a condition, where it adds some HTML code into progress div.

Finally we call our AJAX function, where we pass the "name" value to our file data.php through URL. data.php file echoes some values and inserts name into our database.

We call this echoed values and display it in our table.

data.php code


$name = $_REQUEST['name'];

$con = mysql_connect("localhost","root","");

mysql_select_db("test", $con);

$sql = 'INSERT INTO `test`.`name` (`ID`, `Name`) VALUES (NULL,"'.$name.'")';

if (!mysql_query($sql,$con))
die('Error: ' . mysql_error());
$sqlnew = 'SELECT * from name;';
$res = mysql_query($sqlnew);
echo '<tr><th>Name:</th></tr>';
while($row = mysql_fetch_array($res))
echo '<tr><td>'.$row['Name'].'</td></tr>';



Here we are learning the basics of JQUERY AJAX, if you understand the main concept and the flow of AJAX with PHP, then with the help of google you can make many ajax driven programs.

Final Output:



Oct 25, 2011

How to use Views Slideshow in Drupal 7

1. Required Modules (Version: Drupal 7.8)

  1. Views (7.x-3.0-rc1)
  2. Views Slideshow (7.x-3.x-dev)
  3. Chaos tool suite (7.x-1.0-rc1)
  4. Libraries (7.x-1.0)
  5. Link (7.x-1.0)
  6. Token (7.x-1.0-beta6)

2. Install the Modules

In Drupal 7 you can install modules from the admin section, but I still feel this new feature doesn't have any meaning, because we have to search for the module link in the Drupal site and then copy paste into the admin module installation area, it would have been so good if they would have made it something like WordPress a small search feature. Anyway I just gonna download and install it in the old way (I still recommend this old way).
Download all the above listed modules from and install in the directory

Go to and enable these modules as below:

Modules - Drupal
Enable Modules
  2. Views UI
  3. Views Slideshow
  4. Views Slideshow: Cycle
  5. Chaos tools
  6. Libraries
  7. Link
  8. Token

3. Create Image Cache

In Drupal 7 imagecache is part of core module and is named as Image styles. So let's create two image cache from here, one for the full size slider image and other for the thumbnail image. In this tutorial I use 640x480 (pixels) dimension for the full size slider image and 320x240 (pixels) dimension for the thumbnail image. Note: These configurations can be defered depends on your needs.

Fullsize Slider image settings

Go to and click on the add new style link

  1. Give an Image style name and click on create new style button.
  2. On the next configuration screen select new style you want and then click add button (In this tutorial I choose re-size style).
  3. On the next screen set the width and height and click on the add effect button. (The settings may vary depend on the style you choose). I set width as 640 and height as 480 pixels.
  4. Do this same process for the thumbnail image too. (for the thumbnail image dimension, I set width as 320 and height as 240 pixels.)

4. Create New Content Type

Let's create a new content type, from the dashboard menu bar cick on Structure and then Content types then click on the add new content type link.

  1. Give a human-readable name, I named it as Featured Slider (machine name will be auto generated based on the human readable name)
  2. Give a brief and relevant description
  3. Submission form settings, I leave as the default settings
  4. Publishing options, I checked only published (all other settings unchecked)
  5. Display settings, I have unchecked the authour and date info.
  6. Comment settings, I set hidden (disabled)
  7. Menu settings, I leave as default settings.
  8. Click Save and add fields Button

5. Create New Fields

Here in this example I'll create only two fileds, and they are image field and link field. We will use image field for uploading our slider image and link field for creating a custom link where we want our slider to be linked.

  1. Image Field Settings
  2. Label: Slider Image
  3. Field: slider_image
  4. Field type: image
  5. Widget (form element): image
  6. Click Save button, and on the field settings page leave default settings and click on Save field settings button.
  7. On the image field configuration settings page you can configure as you wish.
  • I set this field as required, I added a file director name called slider-image so that this images will be arranged separately from other images.
  • You can set the maximum upload size and resolution here, I have enabled alt and title field and finally click Save settings button.

By using same method create the link field too.

Link Field Settings:

  1. Label: Slider Link
  2. Field: slider_link
  3. Field type: link
  4. Widget (form element): link
  5. Click "Save" button

Note: For the link field configurations leave everything to default settings.

I have re arranged the field like shown below:

  • Title field
  • Image field
  • Link field
  • Body field (you can even remove this field if not necessary)

Manage Display

On the manage display tab you can conigure how the out put of the field to be diplayed, I have set the image label as hidden.

6. Create Feature Slider Content

I have created four featured slider content for this tutorial.

  1. Click on add content link
  2. Create Featured Slider content
  3. Give a proper title name
  4. Upload slider image
  5. Give alt and title field names
  6. Give a link title and url where you want the slider to be linked
  7. Leave all othe settings as default except for the path field if you want you can give an SEO friendly URL alias.
  8. Save the content.

Repeat the steps twice or thrice to create some more featured slider contents for your slide (I have created four contents)

7. Create a New View

Now it's time to create our new Slideshow view. From the Dashboard menu click on the Structure and then click on the Views.

  1. Click add new view link
  2. Give view name, I have named as Featured Slider (machiine name will be auto generated)
  3. Give an apropriate view description
  4. Choose Show Content of type Featured Slider (your content type name).
  5. Uncheck Create a Pge and check Create a block
  6. Type in Block title and choose display format as "Slideshow" of "fields" items per page 5 (you can enter the number of items you want to display)
  7. Click the button "Continue & edit"

Views Field Settings

  • Add "Link" Field
  1. "Link" must be the first field in order to work everything properly, so click on the add icon and from the filter Groups select "Content"
  2. Add Content: "Link" "Appears in: node:featured_slider."
  3. Click: "Add & configure button"
  4. In the next cofiguration window uncheck "Create a label" and check "Exclude from display"
  5. Click "Apply button".
  • Add "Image" Field
  1. Click on the add icon and from the filter Groups select "Content"
  2. Add Content: "Image" "Appears in: node:featured_slider." (Note: Make sure you choose the "Image" field which we created for this slider content type only.)
  3. Click "Add & configure button"
  4. In the next cofiguration window uncheck "Create a label"
  5. Formatter: "Image" (If you have installed "Colorbox" or "Lightbox2" you can choose them here.)
  6. Image Style: "Fullsize" (Choose the imagecache you have created in the above step "3. Create Image Cache")
  7. Link image to: "Nothing"
  8. Style Settings: "Leave default settings"
  9. No result behaviour: "Leave default settings"
  10. Rewrite Results: Check "Output this field as a link"
  11. Link path: [view_node] (Note: Scroll dow a bit and you can see replacement patterns created by Token module, (If we didn't set the link field as first we can't see link field option here) copy only [view_node] then scroll up and paste it in the link path field.)
  12. Click "Apply button".
  • Add "Thumbnail" Field
  1. Click on the add icon and from the filter Groups select "Content"
  2. Add Content: "Image" "Appears in: node:featured_slider." (Note: Make sure you choose the "Image" field which we created for this slider content type only.)
  3. Click "Add & configure button"
  4. In the next cofiguration window uncheck "Create a label" and check "Exclude from display"
  5. Formatter: "Image" (If you have installed "Colorbox" or "Lightbox2" you can choose them here.)
  6. Image Style: "Thumbnail" (Choose the imagecache you have created in the above step "3. Create Image Cache")
  7. Link image to: "Nothing"
  8. Style Settings: "Leave default settings"
  9. No result behaviour: "Leave default settings"
  10. Rewrite Results: Check "Output this field as a link"
  11. Link path: [view_node] (Note: Scroll dow a bit and you can see replacement patterns created by Token module, (If we didn't set the link field as first we can't see link field option here) copy only [view_node] then scroll up and paste it in the link path field.)
  12. Click "Apply button".

Views Filters Settings

In Views 3.x the filters are created in the beginning while we choose the content type and other settings. If you need any additional filtering you can create it here.

Views Style Settings

Click on the "Format Slideshow Settings" and on the next configuration window set as below:

  • List type: "Unordered list"
  • Wrapper class: "Leave default settings"
  • Style » Skin: "Deafult"
  • Slides » Slideshow type: "Cycle"

"Cycle Options"

You need to download jQuery cycle plugin and copy jquery.cycle.all.min.js to sites/all/libraries/jquery.cycle You can find the plugin at

In a Simpler Manner

Create a folder named "libraries" in your "" directory and then create an another folder named "jquery.cycle" in that directory and finally copy and paste only the "jquery.cycle.all.min.js" into this directory. For e.g.

  • Transittion: "Fade"
  • Action: "Pause on Hover"
  • Internet Explorer Tweaks: "Default"
  • Widgets: You can choose either or both Top and Bottom (I choose bottom here, and the advance settings as below:)
  • Bottom Widgets » Pager » Pager type: "Fields"
  • Pager field » Content: "Image" (Note: Last one we added for the thumb, don't mistake since both field will be named same.)
  • Activate Slide and Pause on Pager Hove: Checked » "Controls" and Unchecked » "Slider Counter"
  • Click on "Apply button".

Format Show Field Settings

  • Inline fields: "Choose the thumbnail field as inline."
  • Click on "Apply button." (Note: Well it actually doesn't change much in appearance but it does change in the code.)

8. Enable & Configure the Block

Now this block will be visible in the blocks disabled area, so from the Dashboard menu go to Structure » Block and "Enable" the block to a themes default region or any of the custom region you've created. (Regions varies depends on the theme you are using.)

Block Configuration Settings

After enabling the block you get a link to configure the block so click on the "Configure" link and on the settings section set as below;

  • Block title (If you don't want block title to be displayed just type <none>)
  • Again you get all enabled theme specific Region settings.

On Visibility Setings

  • Pages » Show block on specific page: choose Only the listed pages and typeso that this block will be displayed only on the front page.

Oct 21, 2011

PHP Multidimensional Array Shuffle | Shuffle Array In PHP

Multi-Dimensional array is an array within array. It is the most common used php function to store multiple values within a variable.

Here is my small snippet share for shuffling multidimentional array values.

Just call this function and pass the multidimensional array through parameters.

[php]public static function shuffle_array($array)
if (!is_array($array)) return $array;
$keys = array_keys($array);
$random = array();
foreach ($keys as $key) {
$shuffle[] = $array[$key];
return $shuffle;

Oct 7, 2011

Must have modules for creating a site in Drupal 7.x


This suite is primarily a set of APIs and tools to improve the developer experience. It also contains a module called the Page Manager whose job is to manage pages. In particular it manages panel pages, but as it grows it will be able to manage far more than just Panels.

Custom Breadcrumbs

Allows administrators to set up parametrized breadcrumb trails for any node type. This allows CCK-style node types to have "Home > User Blog > 2005 > January" style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases. Breadcrumb visibility can be customized via a php snippet.

No new features are planned for these versions, but they are still supported and bug reports are encouraged.


The Fivestar voting module adds a clean, attractive voting widget to nodes in Drupal 5, node and comments in Drupal 6, and any entity in Drupal 7


The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.


The Pathauto module automatically generates path aliases for various kinds of content (nodes, categories, users) without requiring the user to manually specify the path alias. This allows you to get aliases like /category/my-node-title.html instead of /node/123. The aliases are based upon a "pattern" system which the administrator can control.


This module implements the Porter stemming algorithm to improve English-language searching with the Drupal built-in Search module.

The process of stemming reduces each word in the search index to its basic root or stem (e.g. 'blogging' to 'blog') so that variations on a word ('blogs', 'blogger', 'blogging', 'blog') are considered equivalent when searching. This generally results in more relevant search results.


The rules modules allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules).


Tokens are small bits of text that can be placed into larger documents via simple placeholders, like %site-name or [user]. The Token module provides a central API for modules to use these tokens, and expose their own token values.


The Views module provides a flexible method for Drupal site designers to control how lists and tables of content (nodes in Views 1, almost anything in Views 2) are presented. Traditionally, Drupal has hard-coded most of this, particularly in how taxonomy and tracker lists are formatted.

This tool is essentially a smart query builder that, given enough information, can build the proper query, execute it, and display the results. It has four modes, plus a special mode, and provides an impressive amount of functionality from these modes.

Among other things, Views can be used to generate reports, create summaries, and display collections of images and other content.


Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.

Sep 11, 2011

Fully AJAX Alphabetical Sorting | Sorting Titles Alphabetical Using AJAX

AJAX? What the hell is AJAX? In short, the script which fetches data from database without refreshing the page is AJAX. AJAX's full form is Asynchronous JavaScript And XML. The best AJAX example you can find is GMAIL.

OK, so today I am sharing with you a tutorial where with the help of AJAX you will call all titles from the database and display it in Alphabetical order.

First, we will create a database, in my case its ci. inside it we will create two fields ID and title. Give ID as primary key and set it to auto increment.

Then fill the tables with some dummy data.

After that make a folder named as ajax and create following files in it.

  1. newContent.php

  2. index.php

Now Open index.php and paste the following code in it:-


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="" xml:lang="en" lang="en">
<title>WebsTutorial Fully AJAX Sorting</title>
<style type="text/css">

cursor: pointer;
#content1{border:2px solid #e7e7e7; background:#e3e3e3;padding:8px;
background-position:left top;

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<script type="text/javascript">

jQuery(function($) {
$(document).ready(function() {
$(".letter").bind('click', function(){
$("#Loading").fadeIn(); //show when submitting
var val = $(".letter").val;

$("#Loading").fadeOut('fast'); //hide when data's ready

<div id="ajax">

<div id="Loading"><img src="loader.gif" /></div>
<div id="content"></div>


In the above code, rest is just basic HTML but the main thing is AJAX calling.

  • First we are creating a function where, onclick event of letter class, a variable is declared and the clicked letter value is stored in newly created variable.

  • Then we call AJAX and pass the variable to the newContent.php file.

  • newContent.php file takes the value and checks into database and returns back database value to the AJAX function.

  • Then finally database passed value is displayed in #content div.

Now we will write some code in newContent.php file.

Paste the following code in it:-

echo $_GET['letter'];
echo '<br>';
echo '<br>';
$getLetter = $_GET['letter'];

$con = mysql_connect('localhost', 'root', '');
mysql_select_db("ci", $con);
$result = mysql_query('SELECT * FROM test where title LIKE "'.$getLetter.'%"');

while($row = mysql_fetch_array($result))
echo $row['title'] . '<br>';


  • First we store the value of letter passed from AJAX to a variable named as $getLetter.

  • Then we open a connection to the database, please edit this piece of code according to your database name, user and password.

  • After opening the connection, we fire a SQL query where we state, fetch all the title where the first letter starts from $getLetter.

  • As it will return in array, so we will split it with the help of while loop.

  • Done the echoed value will be displayed in the index.php file.

This tutorial explain how basic AJAX works, you will find that in some place the image loading code is written, thats nothing but a loading image, which will appear when data is heavy and takes time to fetch.

Final Output:



JQuery Color Changing Background | JQuery Continous Color Change | JQuery Rainbow

In today's tutorial, I am going to share an easy way to change the background color of a page in infinite loops. In other words, change the background to rainbow.

Concept:The actual logic behind changing the color in infinite loops, is to get infinite colors. So trick is simple, take a RGB pattern and keep on changing the color code. So for that a logic of RGB code is written in jquery.color.js

So the index javascript consists of two major codes.


var rainbow = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';


We are creating a variable named as rainbow and setting its value to rgb(random numbers). They are calculated and by using math.round and math.floor functions, the decimals are removed from it.

The last important thing is to append the color to the background of an HTML element.

$('#welcome').animate( { backgroundColor: rainbow }, 1000);
The most important thing is how to get into infinite loops?????

Simple, within the function declare the same function, which will give us infinite loop.

So the entire javascript function will be.

<script type="text/javascript">// <![CDATA[
$(document).ready(function() {


function spectrum(){
var rainbow = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
$('#welcome').animate( { backgroundColor: rainbow }, 1000);

// ]]></script>

Sep 2, 2011

Wordpress Show Excerpt Of Child Page | How To Show Excerpt Of Child Pages On Parent Page Of Wordpress

Today in this tutorial I am going to share a wordpress hack, which will show your child pages excerpts with title on the parent page.

OK, it was confusing, let me explain you.
Suppose you have  5 pages, which has a single parent page. If you want to show all the 5 sub pages on the Parent page, then you have to use this code.

Open your page.php file and paste this code after the loop.

$child_pages = $wpdb->get_results("SELECT *  FROM $wpdb->posts WHERE post_parent = ".$post->ID."   AND post_type = 'page' ORDER BY menu_order", 'OBJECT'); ?>
<?php if ( $child_pages ) : foreach ( $child_pages as $pageChild ) : setup_postdata( $pageChild ); ?>
<div style="border:1px solid #e7e7e7;margin: 10px;padding: 10px;">
<h2><a href="<?php echo  get_permalink($pageChild->ID); ?>" title="<?php echo $pageChild->post_title; ?>"><?php echo $pageChild->post_title; ?></a></h2>
$your_custom_field = get_post_meta($pageChild->ID, 'your_custom_field', $single = true);
<?php the_excerpt();?>
<p style="text-align:right;"><a href="<?php echo  get_permalink($pageChild->ID); ?>" rel="bookmark" title="<?php echo $pageChild->post_title; ?>">Read More...</a></p>
<?php endforeach;

Aug 22, 2011

How To Make A Shoutbox Using PHP & MYSQL | Create A Shout Box Using PHP MYSQL | Make A Simple Shout Box

First of all, let me explain you what is a shoutbox.

A Shoutbox is nothing but a chat program, where anyone can chat with any anonymous user.
You can read more about shoutbox at this link :

So lets make a shoutbox.

We will make this shoutbox in basic php and mysql.

First you need to make a database where you will store this chats, so from phpmyadmin you can create a databse.
Next we will add a table, so in sql query window, just paste the below code:

CREATE TABLE `shoutbox` (
`name` VARCHAR(45) NOT NULL,
`email` VARCHAR(60) NOT NULL,
`ipaddress` VARCHAR(45) NOT NULL,


Here we made a table with name, email, id and ipaddress fields, where all values is must, id is set to auto increement and we are using IP address to track the user.

Next we will create a file named as db.php, where we make our MYSQL Connection, so just paste the below code in your file db.php


$host = 'localhost'; //Normally localhost
$username = 'root'; //Username which is added to your database, root is default
$password = ''; //Password for your user, for root password is null
$database = 'shoutbox'; //your database name


Now we will create our actual shoutbox code file, make a file and name it to index.php, and add following code in it

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shoutbox From WebsTutorial</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<div id="container">

<h5><a href="" title="WebsTutorial">WebsTutorial</a></h5>

<div id="boxtop"></div>
<div id="content">

$self = $_SERVER['PHP_SELF']; //the $self variable equals this file
$ipaddress = ("$_SERVER[REMOTE_ADDR]"); //the $ipaddress var equals users IP
include ('db.php'); // for db details

// defines a $connect variable, which when used
// will attempt to connect to the databse using
// details provided in config.php
// if it fails, will display error - or die();
$connect = mysql_connect($host,$username,$password) or die('<p>Unable to connect to the database server at this time.</p>');

// connect to database using details provided
// and uses the $connect variable above
// if it fails, will return error - or die();
mysql_select_db($database,$connect) or die('<p>Unable to connect to the database at this time.</p>');

// checks the POST to see if something has been submitted
if(isset($_POST['send'])) {
// are any of the fields empty? the || means 'or'
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['post'])) {
echo('<p>You did not fill in a required field.</p>');
} else {

// if there are no empty fields, insert into the database:

// escape special characters to stop xss and sql injecting
// we take the 'name' and 'post' parts from the POST
// and run it through htmlspecialchars()
// this stops users sending HTML code, as it could be malicious
// also runs through mysql_real_escape_string()
// stops users sending SQL code, which could be used to access the db
$name = htmlspecialchars(mysql_real_escape_string($_POST['name']));
$email = htmlspecialchars(mysql_real_escape_string($_POST['email']));
$post = htmlspecialchars(mysql_real_escape_string($_POST['post']));

// this is our SQL string to insert shouts into db
$sql = "INSERT INTO shouts SET name='$name', email='$email', post='$post', ipaddress='$ipaddress';";

// we run the SQL string now
// if it succeeds, display message
if (@mysql_query($sql)) {
echo('<p>Thanks for shouting!</p>');
} else {
// if it errors, send message
echo('<p>There was an unexpected error when posting your shout.</p>');

// now we retrieve the 8 latest shouts from the db
$query = "SELECT * FROM shouts ORDER BY `id` DESC LIMIT 8;";

// run the query. if it fails, display error
$result = @mysql_query("$query") or die('<p>There was an unexpected error grabbing shouts from the database.</p>');

// while we still have rows from the db, display them
while ($row = mysql_fetch_array($result)) {

$ename = stripslashes($row['name']);
$eemail = stripslashes($row['email']);
$epost = stripslashes($row['post']);

// Woop! We can use Gravatars aswell!!
$grav_url = "".md5(strtolower($eemail))."&size=70";

echo('<li><div><p>'.$ename.'</p><img src="'.$grav_url.'" alt="Gravatar" /></div><div><p style="padding:20px 0 0 0;">'.$epost.'</p></div></li>');


<!-- at the bottom of the page, we display our comment form -->
<form action="<?php $self ?>" method="post">
<div><label for="name"><p>Name:</p></label><input name="name" type="text" cols="20" /></div>
<div><label for="email"><p>Email:</p></label><input name="email" type="text" cols="20" /></div>
<textarea name="post" rows="5" cols="40"></textarea>
<input name="send" type="hidden" />
<p><input type="submit" value="send" /></p>

<div id="boxbot"></div>



OK, in this file first we get the IP address of the person and open the db connection by including our first created db.php file.

Then we pass a check condition to check the emptiness in the textboxes. And we also store the values in respective variables, here while storing them we are using php functions htmlspecialchars, to avoid html characters and mysql_real_escape_string to avoid sql statements, this two are very important in terms of security else anyone will pass html and sql codes and pamper the database or server.

After storing them, we finally code the insert query and echoes a custom message of successful execution.

Wait a minute, this is not the end, now we will also have to display the recently 8 shouts, so we fire a select query and  store the array in a variable.

And finally in a while loop we echo the email, name and the shout message.

Woila, done, but arghhhhhhhhhhh without CSS, its like image without color, so make a file style.css and add the following css code in it.

/* Shoutbox PHP tutorial from WebsTutorial */

* {
margin: 0;
padding: 0;

body {
background: #323f66 top center url("images/back.png") no-repeat;
color: #ffffff;
font-family: Helvetica, Arial, Verdana, sans-serif;

h1 {
font-size: 3.5em;
letter-spacing: -1px;
background: url("images/shoutbox.png") no-repeat;
width: 303px;
margin: 0 auto;
text-indent: -9999em;
color: #33ccff;

h2 {
font-size: 2em;
letter-spacing: -1px;
background: url("images/shout.png") no-repeat;
width: 119px;
text-indent: -9999em;
color: #33ccff;
clear: both;
margin: 15px 0;

h5 a:link, h5 a:visited {
color: #ffffff;
text-decoration: none;

h5 a:hover, h5 a:active, h5 a:focus {
border-bottom: 1px solid #fff;

p {
font-size: 0.9em;
line-height: 1.3em;
font-family: Lucida Sans Unicode, Helvetica, Arial, Verdana, sans-serif;

p.error {
background-color: #603131;
border: 1px solid #5c2d2d;
width: 260px;
padding: 10px;
margin-bottom: 15px;

p.success {
background-color: #313d60;
border: 1px solid #2d395c;
width: 260px;
padding: 10px;
margin-bottom: 15px;

#container {
width: 664px;
margin: 20px auto;
text-align: center;

#boxtop {
margin: 30px auto 0px;
background: url("images/top.png") no-repeat;
width: 663px;
height: 23px;

#boxbot {
margin: 0px auto 30px;
background: url("images/bot.png") no-repeat;
width: 664px;
height: 25px;

#content {
margin: 0 auto;
width: 664px;
text-align: left;
background: url("images/bg.png") repeat-y;
padding: 15px 35px;

#content ul {
margin-left: 0;
margin-bottom: 15px;

#content ul li {
list-style: none;
clear: both;
padding-top: 30px;

#content ul li:first-child {

.meta {
width: 85px;
text-align: left;
float: left;
min-height: 110px;
font-weight: bold;

.meta img {
padding: 5px;
background-color: #313d60;

.meta p {
font-size: 0.8em;

.shout {
width: 500px;
float: left;
margin-left: 15px;
min-height: 110px;
padding-top: 5px;

form {
clear: both;
margin-top: 135px !important;

.fname, .femail {
width: 222px;
float: left;

form p {
font-weight: bold;
margin-bottom: 3px;

form textarea {
width: 365px;
overflow: hidden; /* removes vertical scrollbar in IE */

form input, form textarea {
background-color: #313d60;
border: 1px solid #2d395c;
color: #ffffff;
padding: 5px;
font-family: Lucida Sans Unicode, Helvetica, Arial, Verdana, sans-serif;
margin-bottom: 10px;

ul li{
border: 1px solid #2A3556;
float: left;
margin-right: 10px;
padding: 10px;
position: relative;
right: 12px;

This was your last step by styling the shoutbox.
Feel free to ask any questions if you didn't understand any point or if I missed something

Final Layout:

WebsTutorial Shoutbox