<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0"><channel><title>InTechgrity » Featured</title> <link>http://www.intechgrity.com</link> <description>Amalgamating Life &amp; Technology</description> <lastBuildDate>Fri, 25 May 2012 04:37:18 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.2</generator> <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/InTechgrity-Featured" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="intechgrity-featured" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">InTechgrity-Featured</feedburner:emailServiceId><feedburner:feedburnerHostname xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://feedburner.google.com</feedburner:feedburnerHostname><item><title>Automatically copy images (png, jpeg, gif) from remote server (http) to your local server using PHP</title><link>http://www.intechgrity.com/automatically-copy-images-png-jpeg-gif-from-remote-server-http-to-your-local-server-using-php/</link> <comments>http://www.intechgrity.com/automatically-copy-images-png-jpeg-gif-from-remote-server-http-to-your-local-server-using-php/#comments</comments> <pubDate>Thu, 24 May 2012 17:12:03 +0000</pubDate> <dc:creator>Swashata</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[php]]></category> <category><![CDATA[php-gd]]></category> <category><![CDATA[php-image]]></category><guid isPermaLink="false">http://www.intechgrity.com/?p=808</guid> <description><![CDATA[<p><p>Original post published <a
href="<a href="http://www.intechgrity.com/automatically-copy-images-png-jpeg-gif-from-remote-server-http-to-your-local-server-using-php/">Automatically copy images (png, jpeg, gif) from remote server (http) to your local server using PHP</a>">here</a></p><p>So, have you ever found the necessity to copy remote images to your local server using http URLs? This is pretty easy using PHP and PHP GD. If you have both of them installed (in most of the servers they come installed) then you can do that in no time. But then comes the security [...]</p></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p> No related posts.]]></description> <content:encoded><![CDATA[<p>Original post published <a
href="<a href="http://www.intechgrity.com/automatically-copy-images-png-jpeg-gif-from-remote-server-http-to-your-local-server-using-php/">Automatically copy images (png, jpeg, gif) from remote server (http) to your local server using PHP</a>">here</a></p><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/copy-image-php-remote-local.png"><img
class="alignright  wp-image-1186" title="copy-image-php-remote-local" src="http://www.intechgrity.com/wp-content/uploads/2012/05/copy-image-php-remote-local.png" alt="" width="235" height="235" /></a>So, have you ever found the necessity to copy remote images to your local server using http URLs? This is pretty easy using PHP and PHP GD. If you have both of them installed (in most of the servers they come installed) then you can do that in no time. But then comes the security issue. Copying anything from remote server to your local server can expose your server to many vulnerabilities. Just like, recently our site got hacked due to TimThumb vulnerability. So, we decided to put together a working code which you can use on your projects to copy any valid images from remote to local server. The copying process is pretty much automatic given our code. We have wrapped them in a function and it is available for you to download as well. We shall now discuss the working of the method. But before that:</p><div
class="demo-download"><a
class="demo" href="http://demo.intechgrity.com/fetch-image/" target="_blank">Demo</a><a
class="download" title="Copy Remote Images using PHP Downloaded 4" href="http://www.intechgrity.com/downloads/14">Download Now</a></div><h2>#1: Understanding the concept:</h2><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/concept-function.png"><img
class="aligncenter size-full wp-image-1190" title="concept-function" src="http://www.intechgrity.com/wp-content/uploads/2012/05/concept-function.png" alt="" width="560" height="150" /></a>While creating such automated script, we should think of a few things. Or in other words, while creating the function, we should think of the parameters first.</p><ul><li><strong>$img_url</strong>: The URL of the image. We should accept URLs starting with http:// or https:// and ending with .png, .jpg, .jpeg or .gif. Others should be rejected.</li><li><strong>$store_dir</strong>: The directory where we should store the images.</li><li><strong>$store_dir_type</strong>: Should specify whether the directory path is relative to the script or is absolute.</li><li><strong>$overwrite</strong>: In case of duplicate file name, should it overwrite?</li><li><strong>$pref</strong>: Internally used for dynamic renaming of duplicate files using tail recursion  (a function, directly returns the same function call with some different arguments).</li><li><strong>$debug</strong>: A little bit of debug information is always fun, and well, informative.</li></ul><p>So, keeping these things, we write in the skeleton of our function.</p><pre class="brush: php; title: ; notranslate">
/**
 * Fetch JPEG or PNG or GIF Image
 *
 * A custom function in PHP which lets you fetch jpeg or png images from remote server to your local server
 * Can also prevent duplicate by appending an increasing _xxxx to the filename. You can also overwrite it.
 *
 * Also gives a debug mode to check where the problem is, if this is not working for you.
 *
 * @author Swashata &lt;swashata ~[at]~ intechgrity ~[dot]~ com&gt;
 * @copyright Do what ever you wish - I like GPL <img src='http://www.intechgrity.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  (&amp; love tux <img src='http://www.intechgrity.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> )
 * @link http://www.intechgrity.com/?p=808
 *
 * @param string $img_url The URL of the image. Should start with http or https followed by :// and end with .png or .jpeg or .jpg or .gif. Else it will not pass the validation
 * @param string $store_dir The directory where you would like to store the images.
 * @param string $store_dir_type The path type of the directory. 'relative' for the location in relation with the executing script location or 'absolute'
 * @param bool $overwrite Set to true to overwrite, false to create a new image with different name
 * @param bool|int $pref internally used to prefix the extension in case of duplicate file name. Used by the trailing recursion call
 * @param bool $debug Set to true for enable debugging and print some useful messages.
 * @return string the location of the image (either relative with the current script or abosule depending on $store_dir_type)
 */
function itg_fetch_image($img_url, $store_dir = 'image', $store_dir_type = 'relative', $overwrite = false, $pref = false, $debug = false) {
    //code
}
</pre><h2>#2: Verifying the image URL:</h2><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/validate-image-security.png"><img
class="aligncenter size-full wp-image-1189" title="validate-image-security" src="http://www.intechgrity.com/wp-content/uploads/2012/05/validate-image-security.png" alt="" width="560" height="150" /></a>This should be done before anything else. What we do is:</p><ul><li>Check if the URL begins with <span
class="spanlight">http://</span> or <span
class="spanlight">https://</span>. Reject otherwise.</li><li>Check if the URL ends with a valid extension (<span
class="spanlight">.gif</span>, <span
class="spanlight">.jpeg</span>, <span
class="spanlight">.jpg</span>, <span
class="spanlight">.png</span>). Reject otherwise.</li></ul><p>We shall use PHP&#8217;s built in <span
class="code">preg_match</span> to search using our regular expression. The code snippet for validating the image URL is this:</p><pre class="brush: php; title: ; notranslate">
    if(preg_match('/https?:\/\/.*\.png$/i', $img_url)) {
        $img_type = 'png';
    }
    else if(preg_match('/https?:\/\/.*\.(jpg|jpeg)$/i', $img_url)) {
        $img_type = 'jpg';
    }
    else if(preg_match('/https?:\/\/.*\.gif$/i', $img_url)) {
        $img_type = 'gif';
    }
    else {
        if(true == $debug)
            echo 'Invalid image URL';
        return ''; //possible error on the image URL
    }
</pre><h2>#3: Handling duplicate files:</h2><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/handle-duplicate-files.png"><img
class="aligncenter size-full wp-image-1191" title="handle-duplicate-files" src="http://www.intechgrity.com/wp-content/uploads/2012/05/handle-duplicate-files.png" alt="" width="560" height="150" /></a>As mentioned before, we should handle duplicate files properly. The strategy is:</p><ul><li>Somehow use smart renaming by appending _xxx (xxx is a counter) after the image name and before the extension. We shall increase the counter unless a valid non-existing filename is found.</li><li>Or, delete the old file altogether if overwriting is set to true.</li></ul><p>And here is the code snippet which does the trick:</p><pre class="brush: php; title: ; notranslate">
    //first get the base name of the image
    $i_name = explode('.', basename($img_url));
    $i_name = $i_name[0];

    $dir_name = (($store_dir_type == 'relative')? './' : '') . rtrim($store_dir, '/') . '/';

    //create the directory if not present
    if(!file_exists($dir_name))
        mkdir($dir_name, 0777, true);

    //calculate the destination image path
    $i_dest = $dir_name . $i_name . (($pref === false)? '' : '_' . $pref) . '.' . $img_type;

    //lets see if the path exists already
    if(file_exists($i_dest)) {
        $pref = (int) $pref;

        //modify the file name, do not overwrite
        if(false == $overwrite)
            return itg_fetch_image($img_url, $store_dir, $store_dir_type, $overwrite, ++$pref, $debug);
        //delete &amp; overwrite
        else
            unlink ($i_dest);
    }
</pre><p>Note that it intelligently uses tail recursion for smart renaming. It simply returns the same function by incrementing the value of <span
class="code">$pref</span> variable by 1.</p><h2>#4: Fetching the image from the server:</h2><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/fetch-from-remote-server.png"><img
class="aligncenter size-full wp-image-1187" title="fetch-from-remote-server" src="http://www.intechgrity.com/wp-content/uploads/2012/05/fetch-from-remote-server.png" alt="" width="560" height="150" /></a>Now comes the real thing. We will now see how we can fetch the image from the remove server using some built in PHP GD functions. Note that for all these to work, you will need fopen wrapper enabled, which is enabled in most of the servers. If not, then you can edit your <span
class="spanlight">php.ini</span> file and set it to true. <a
href="http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen" target="_blank">Check here</a> for more information. So, here is the code snippet which does the magic:</p><pre class="brush: php; title: ; notranslate">
    //first check if the image is fetchable
    $img_info = @getimagesize($img_url);

    //is it a valid image?
    if(false == $img_info || !isset($img_info[2]) || !($img_info[2] == IMAGETYPE_JPEG || $img_info[2] == IMAGETYPE_PNG || $img_info[2] == IMAGETYPE_JPEG2000 || $img_info[2] == IMAGETYPE_GIF)) {
        if(true == $debug)
            echo 'The image doesn\'t seem to exist in the remote server';
        return ''; //return empty string
    }

    //now try to create the image
    if($img_type == 'jpg') {
        $m_img = @imagecreatefromjpeg($img_url);
    } else if($img_type == 'png') {
        $m_img = @imagecreatefrompng($img_url);
        @imagealphablending($m_img, false);
        @imagesavealpha($m_img, true);
    } else if($img_type == 'gif') {
        $m_img = @imagecreatefromgif($img_url);
    } else {
        $m_img = FALSE;
    }

    //was the attempt successful?
    if(FALSE === $m_img) {
        if(true == $debug)
            echo 'Can not create image from the URL';
        return '';
    }
</pre><h2>#5: Saving the image locally on disk:</h2><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/save-image-local-disk.png"><img
class="aligncenter size-full wp-image-1188" title="save-image-local-disk" src="http://www.intechgrity.com/wp-content/uploads/2012/05/save-image-local-disk.png" alt="" width="560" height="150" /></a>Now finally we would save the image locally on our disk. The snippet is:</p><pre class="brush: php; title: ; notranslate">
    //now attempt to save the file on local server
    if($img_type == 'jpg') {
        if(imagejpeg($m_img, $i_dest, 100))
            return $i_dest;
        else
            return '';
    } else if($img_type == 'png') {
        if(imagepng($m_img, $i_dest, 0))
            return $i_dest;
        else
            return '';
    } else if($img_type == 'gif') {
        if(imagegif($m_img, $i_dest))
            return $i_dest;
        else
            return '';
    }
</pre><p>Note that you can edit the third variable of <span
class="code">imagejpeg</span> and <span
class="code">imagepng</span> to set the quality. More information can be found <a
href="http://in2.php.net/manual/en/function.imagejpeg.php" target="_blank">here</a> or <a
href="http://in2.php.net/manual/en/function.imagepng.php" target="_blank">here</a>.</p><h2>#6: The complete code:</h2><p>So putting together everything, here is the complete code:</p><pre class="brush: php; collapse: true; light: false; title: ; toolbar: true; notranslate">
/**
 * Fetch JPEG or PNG or GIF Image
 *
 * A custom function in PHP which lets you fetch jpeg or png images from remote server to your local server
 * Can also prevent duplicate by appending an increasing _xxxx to the filename. You can also overwrite it.
 *
 * Also gives a debug mode to check where the problem is, if this is not working for you.
 *
 * @author Swashata &lt;swashata ~[at]~ intechgrity ~[dot]~ com&gt;
 * @copyright Do what ever you wish - I like GPL <img src='http://www.intechgrity.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  (&amp; love tux <img src='http://www.intechgrity.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> )
 * @link http://www.intechgrity.com/?p=808
 *
 * @param string $img_url The URL of the image. Should start with http or https followed by :// and end with .png or .jpeg or .jpg or .gif. Else it will not pass the validation
 * @param string $store_dir The directory where you would like to store the images.
 * @param string $store_dir_type The path type of the directory. 'relative' for the location in relation with the executing script location or 'absolute'
 * @param bool $overwrite Set to true to overwrite, false to create a new image with different name
 * @param bool|int $pref internally used to prefix the extension in case of duplicate file name. Used by the trailing recursion call
 * @param bool $debug Set to true for enable debugging and print some useful messages.
 * @return string the location of the image (either relative with the current script or abosule depending on $store_dir_type)
 */
function itg_fetch_image($img_url, $store_dir = 'image', $store_dir_type = 'relative', $overwrite = false, $pref = false, $debug = false) {
    //first get the base name of the image
    $i_name = explode('.', basename($img_url));
    $i_name = $i_name[0];

    //now try to guess the image type from the given url
    //it should end with a valid extension...
    //good for security too
    if(preg_match('/https?:\/\/.*\.png$/i', $img_url)) {
        $img_type = 'png';
    }
    else if(preg_match('/https?:\/\/.*\.(jpg|jpeg)$/i', $img_url)) {
        $img_type = 'jpg';
    }
    else if(preg_match('/https?:\/\/.*\.gif$/i', $img_url)) {
        $img_type = 'gif';
    }
    else {
        if(true == $debug)
            echo 'Invalid image URL';
        return ''; //possible error on the image URL
    }

    $dir_name = (($store_dir_type == 'relative')? './' : '') . rtrim($store_dir, '/') . '/';

    //create the directory if not present
    if(!file_exists($dir_name))
        mkdir($dir_name, 0777, true);

    //calculate the destination image path
    $i_dest = $dir_name . $i_name . (($pref === false)? '' : '_' . $pref) . '.' . $img_type;

    //lets see if the path exists already
    if(file_exists($i_dest)) {
        $pref = (int) $pref;

        //modify the file name, do not overwrite
        if(false == $overwrite)
            return itg_fetch_image($img_url, $store_dir, $store_dir_type, $overwrite, ++$pref, $debug);
        //delete &amp; overwrite
        else
            unlink ($i_dest);
    }

    //first check if the image is fetchable
    $img_info = @getimagesize($img_url);

    //is it a valid image?
    if(false == $img_info || !isset($img_info[2]) || !($img_info[2] == IMAGETYPE_JPEG || $img_info[2] == IMAGETYPE_PNG || $img_info[2] == IMAGETYPE_JPEG2000 || $img_info[2] == IMAGETYPE_GIF)) {
        if(true == $debug)
            echo 'The image doesn\'t seem to exist in the remote server';
        return ''; //return empty string
    }

    //now try to create the image
    if($img_type == 'jpg') {
        $m_img = @imagecreatefromjpeg($img_url);
    } else if($img_type == 'png') {
        $m_img = @imagecreatefrompng($img_url);
        @imagealphablending($m_img, false);
        @imagesavealpha($m_img, true);
    } else if($img_type == 'gif') {
        $m_img = @imagecreatefromgif($img_url);
    } else {
        $m_img = FALSE;
    }

    //was the attempt successful?
    if(FALSE === $m_img) {
        if(true == $debug)
            echo 'Can not create image from the URL';
        return '';
    }

    //now attempt to save the file on local server
    if($img_type == 'jpg') {
        if(imagejpeg($m_img, $i_dest, 100))
            return $i_dest;
        else
            return '';
    } else if($img_type == 'png') {
        if(imagepng($m_img, $i_dest, 0))
            return $i_dest;
        else
            return '';
    } else if($img_type == 'gif') {
        if(imagegif($m_img, $i_dest))
            return $i_dest;
        else
            return '';
    }

    return '';
}

//a quick test? just uncomment the line below
//echo itg_fetch_image('http://tuxpaint.org/stamps/stamps/animals/birds/cartoon/tux.png');
</pre><p>You can call it as mentioned there in the comments. Play with the parameters and see what you can do. You can integrate it with PHP POST and GET operations on your live project. Do check our tutorial on <a
title="Using PHP GET and POST simultaneously via single HTML form" href="http://www.intechgrity.com/using-php-get-and-post-simultaneously-via-single-html-form/">PHP POST and GET</a> for a better understanding. Also, the function returns the path of the stored image. You can change this behaviour if you like by simply altering the return statement. The usage is completely upto you.</p><div
class="demo-download"><a
class="demo" href="http://demo.intechgrity.com/fetch-image/" target="_blank">Demo</a><a
class="download" title="Copy Remote Images using PHP Downloaded 4" href="http://www.intechgrity.com/downloads/14">Download Now</a></div><p>So, that was all. If you have any question or need any help with it, then do drop in a comment. I will try my best to give you the support you want.</p><p>No related posts.</p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p>]]></content:encoded> <wfw:commentRss>http://www.intechgrity.com/automatically-copy-images-png-jpeg-gif-from-remote-server-http-to-your-local-server-using-php/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Add home &amp; other items directly in WP Nav Menu using wp_nav_menu_items filters</title><link>http://www.intechgrity.com/add-home-other-items-directly-in-wp-nav-menu-using-wp_nav_menu_items-filters/</link> <comments>http://www.intechgrity.com/add-home-other-items-directly-in-wp-nav-menu-using-wp_nav_menu_items-filters/#comments</comments> <pubDate>Sun, 20 May 2012 07:53:15 +0000</pubDate> <dc:creator>Swashata</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[Wordpress APIs]]></category> <category><![CDATA[wordpress]]></category> <category><![CDATA[wordpress api]]></category> <category><![CDATA[wordpress hacks]]></category><guid isPermaLink="false">http://www.intechgrity.com/?p=1162</guid> <description><![CDATA[<p><p>Original post published <a
href="<a href="http://www.intechgrity.com/add-home-other-items-directly-in-wp-nav-menu-using-wp_nav_menu_items-filters/">Add home &#038; other items directly in WP Nav Menu using wp_nav_menu_items filters</a>">here</a></p><p>So, this is going to be the last of the WordPress Nav Menu series. Previously, we have talked about the basics of WordPress custom navigation menu and dealing the empty nav menus with custom fallbacks. In this post, we shall see how we can directly add some links to the nav menu using filters. This [...]</p></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p> Related posts:<ol><li><a
href='http://www.intechgrity.com/programmers-guide-for-wordpress-nav-menu/' rel='bookmark' title='Programmer&#8217;s guide for WordPress Nav menu'>Programmer&#8217;s guide for WordPress Nav menu</a></li><li><a
href='http://www.intechgrity.com/the-right-way-of-dealing-wp_nav_menu-fallback-function-list-custom-categories-pages/' rel='bookmark' title='The right way of dealing wp_nav_menu fallback function &#8211; List custom categories &amp; pages'>The right way of dealing wp_nav_menu fallback function &#8211; List custom categories &#038; pages</a></li><li><a
href='http://www.intechgrity.com/jquery-powered-sidebar-navigation-menu/' rel='bookmark' title='jQuery Vertical Sidebar Navigation menu for your Blog or Website – Free package by iTg'>jQuery Vertical Sidebar Navigation menu for your Blog or Website – Free package by iTg</a></li><li><a
href='http://www.intechgrity.com/download-web-videos-directly-from-your/' rel='bookmark' title='Download Web Videos directly from your Firefox using Video DownloadHelper'>Download Web Videos directly from your Firefox using Video DownloadHelper</a></li><li><a
href='http://www.intechgrity.com/add-dynamic-login-logout-n-site-admin-button-to-wordpress-using-wp-api/' rel='bookmark' title='Add dynamic Login Logout n Site Admin button to WordPress using WP API'>Add dynamic Login Logout n Site Admin button to WordPress using WP API</a></li></ol>]]></description> <content:encoded><![CDATA[<p>Original post published <a
href="<a href="http://www.intechgrity.com/add-home-other-items-directly-in-wp-nav-menu-using-wp_nav_menu_items-filters/">Add home &#038; other items directly in WP Nav Menu using wp_nav_menu_items filters</a>">here</a></p><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/custom-items-to-wp_nav_menu.png"><img
class="alignright size-thumbnail wp-image-1175" title="custom-items-to-wp_nav_menu" src="http://www.intechgrity.com/wp-content/uploads/2012/05/custom-items-to-wp_nav_menu-150x150.png" alt="" width="150" height="150" /></a>So, this is going to be the last of the WordPress Nav Menu series. Previously, we have talked about the <a
title="Programmer’s guide for WordPress Nav menu" href="http://www.intechgrity.com/programmers-guide-for-wordpress-nav-menu/">basics of WordPress custom navigation menu</a> and <a
title="The right way of dealing wp_nav_menu fallback function – List custom categories &amp; pages" href="http://www.intechgrity.com/the-right-way-of-dealing-wp_nav_menu-fallback-function-list-custom-categories-pages/">dealing the empty nav menus with custom fallbacks</a>. In this post, we shall see how we can directly add some links to the nav menu using filters. This would become useful, if you want to customize the user&#8217;s own navigation menus. We shall see, how we can add the home button and also the dynamic login/logout button through user defined custom navigation menus using WordPress Filters.</p><h2>#1: Understanding the concept:</h2><p>The filter we will be using is <span
class="code">wp_nav_menu_items</span>. It lets the function get two arguments. One is <span
class="code">$items</span>, which is the HTML of all the items in the navigation. Other is the <span
class="code">$args</span>, which holds the information of the nav itself. We shall use the $args variable to identify our target navigation menu and then will add our links.</p><h2>#2: Adding the Navigation menu:</h2><p>First we hook our two navigation menus, <span
class="spanlight">primary</span> &amp; <span
class="spanlight">footer</span> as follows:</p><pre class="brush: php; title: ; notranslate">
/**
 * Register our nav menus
 * @see http://codex.wordpress.org/Function_Reference/register_nav_menus
 */
function my_theme_nav_bars() {
    register_nav_menus(array(
        'primary' =&gt; 'Primary Menu',
        'footer' =&gt; 'Footer Menu',
    ));
}
add_action('init', 'my_theme_nav_bars');
</pre><h2>#3: Add filters to customize:</h2><p>Now, we customize the navigation menus using filters like this:</p><pre class="brush: php; title: ; notranslate">
/**
 * Filter the navigation menus and add customized links
 *
 * We are usign wp_nav_menu_items filter to do this.
 * Also, $args is used to identify the location of the nav menu
 * and change it accordingly.
 *
 * @param string $items The HTML of the generated items
 * @param array $args The information of the navigation
 * @return string
 */
function filter_my_theme_nav_bars($items, $args) {
    if($args-&gt;theme_location == 'primary') {
        $homelink = '&lt;li class=&quot;home' . ((is_home() || is_front_page())? ' current_page_item' : '') . '&quot;&gt;&lt;a href=&quot;' . get_bloginfo('url') . '&quot;&gt;' . __('Home') . '&lt;/a&gt;&lt;/li&gt;';
        $items = $homelink . $items;
    }

    if($args-&gt;theme_location == 'footer') {
        $dlink = '&lt;li class=&quot;login&quot;&gt;' . wp_loginout('', false) . '&lt;/li&gt;' . wp_register('&lt;li class=&quot;admin&quot;&gt;', '&lt;/li&gt;', false);
        $items .= $dlink;
    }

    return $items;
}
add_filter('wp_nav_menu_items', 'filter_my_theme_nav_bars', 10, 2);
</pre><p>The code is quite self explanatory. It adds a nice Home button to the primary nav and nice login/logout button to the footer navigation. We use the <span
class="code">wp_nav_menu_items</span> to hook to the filter. The argument 10 represents the priority, which is the default and 2 represent the number of arguments which should be two (<span
class="code">$items</span> &amp; <span
class="code">$args</span>).</p><p>Now, for the sake of completeness, let us see how we can do even more.</p><h3>#3.1: Add a search bar to the navigation:</h3><pre class="brush: php; title: ; notranslate">
function add_search_through_filter($items, $args) {
    if($args-&gt;theme_location == 'primary') {
        $searchlink = '&lt;li class=&quot;search&quot;&gt;' . get_search_form(false) . '&lt;/li&gt;';
        $items .= $searchlink;
    }
    return $items;
}
add_filter('wp_nav_menu_items', 'add_search_through_filter', 10, 2);
</pre><h3>#3.2: Add feed link to the navigation:</h3><pre class="brush: php; title: ; notranslate">
function add_rss_link_through_filter($items, $args) {
    if($args-&gt;theme_location == 'primary') {
        $rsslink = '&lt;li class=&quot;rss&quot;&gt;&lt;a href=&quot;' . get_bloginfo('rss2_url') . '&quot;&gt;RSS&lt;/a&gt;&lt;/li&gt;';
        $items .= $rsslink;
    }
    return $items;
}
add_filter('wp_nav_menu_items', 'add_rss_link_through_filter', 10, 2);
</pre><h3>#3.3: Show some text:</h3><pre class="brush: php; title: ; notranslate">
function add_custom_text_through_filter($items, $args) {
    if($args-&gt;theme_location == 'footer') {
        $clink = '&lt;li class=&quot;copyright&quot;&gt;&amp;copy; Copyright ' . get_bloginfo('name') . ' ~ 2010-' . date('Y') . '&lt;/li&gt;';
        $items .= $clink;
    }
    return $items;
}
add_filter('wp_nav_menu_items', 'add_custom_text_through_filter', 10, 2);
</pre><p>So, that was all. I hope you found this interesting. If you have any doubt then feel free to ask.</p><p>Related posts:<ol><li><a
href='http://www.intechgrity.com/programmers-guide-for-wordpress-nav-menu/' rel='bookmark' title='Programmer&#8217;s guide for WordPress Nav menu'>Programmer&#8217;s guide for WordPress Nav menu</a></li><li><a
href='http://www.intechgrity.com/the-right-way-of-dealing-wp_nav_menu-fallback-function-list-custom-categories-pages/' rel='bookmark' title='The right way of dealing wp_nav_menu fallback function &#8211; List custom categories &amp; pages'>The right way of dealing wp_nav_menu fallback function &#8211; List custom categories &#038; pages</a></li><li><a
href='http://www.intechgrity.com/jquery-powered-sidebar-navigation-menu/' rel='bookmark' title='jQuery Vertical Sidebar Navigation menu for your Blog or Website – Free package by iTg'>jQuery Vertical Sidebar Navigation menu for your Blog or Website – Free package by iTg</a></li><li><a
href='http://www.intechgrity.com/download-web-videos-directly-from-your/' rel='bookmark' title='Download Web Videos directly from your Firefox using Video DownloadHelper'>Download Web Videos directly from your Firefox using Video DownloadHelper</a></li><li><a
href='http://www.intechgrity.com/add-dynamic-login-logout-n-site-admin-button-to-wordpress-using-wp-api/' rel='bookmark' title='Add dynamic Login Logout n Site Admin button to WordPress using WP API'>Add dynamic Login Logout n Site Admin button to WordPress using WP API</a></li></ol></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p>]]></content:encoded> <wfw:commentRss>http://www.intechgrity.com/add-home-other-items-directly-in-wp-nav-menu-using-wp_nav_menu_items-filters/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Catch the first image on WordPress post and use as thumbnail</title><link>http://www.intechgrity.com/catch-the-first-image-on-wordpress-post-and-use-as-thumbnail/</link> <comments>http://www.intechgrity.com/catch-the-first-image-on-wordpress-post-and-use-as-thumbnail/#comments</comments> <pubDate>Fri, 18 May 2012 16:15:34 +0000</pubDate> <dc:creator>Swashata</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[WP Programming]]></category> <category><![CDATA[wordpress]]></category> <category><![CDATA[wordpress hacks]]></category><guid isPermaLink="false">http://www.intechgrity.com/?p=1144</guid> <description><![CDATA[<p><p>Original post published <a
href="<a href="http://www.intechgrity.com/catch-the-first-image-on-wordpress-post-and-use-as-thumbnail/">Catch the first image on WordPress post and use as thumbnail</a>">here</a></p><p>So this the last (perhaps) continuation of the posts getting the source URL of the featured image and using TimThumb with WordPress MultiSite. As the title says, today we are going to discuss how to automatically fetch the URL of the first image for any WordPress posts or pages and then we shall also see [...]</p></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p> Related posts:<ol><li><a
href='http://www.intechgrity.com/how-to-get-the-souce-url-of-the-featured-image-in-wordpress/' rel='bookmark' title='How to get the souce URL of the featured image in WordPress'>How to get the souce URL of the featured image in WordPress</a></li><li><a
href='http://www.intechgrity.com/setting-post-thumbnail-on-wordpress-with-custom-size-and-cropping-a-simpler-approach/' rel='bookmark' title='Setting Post Thumbnail on WordPress with custom size and Cropping &#8211; A simpler approach'>Setting Post Thumbnail on WordPress with custom size and Cropping &#8211; A simpler approach</a></li><li><a
href='http://www.intechgrity.com/getting-post-thumbnail-on-wordpress-3-w-wo-specific-post-id/' rel='bookmark' title='Getting Post thumbnail on WordPress 3 w/ w/o specific Post ID'>Getting Post thumbnail on WordPress 3 w/ w/o specific Post ID</a></li><li><a
href='http://www.intechgrity.com/wordpress-multisite-compatibility-for-timthumb/' rel='bookmark' title='WordPress Multisite compatibility for timthumb'>WordPress Multisite compatibility for timthumb</a></li><li><a
href='http://www.intechgrity.com/get-post-count-of-a-category-including-sub-categories-in-wordpress/' rel='bookmark' title='Get post count of a category including sub-categories in WordPress'>Get post count of a category including sub-categories in WordPress</a></li></ol>]]></description> <content:encoded><![CDATA[<p>Original post published <a
href="<a href="http://www.intechgrity.com/catch-the-first-image-on-wordpress-post-and-use-as-thumbnail/">Catch the first image on WordPress post and use as thumbnail</a>">here</a></p><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/grab-first-image-from-a-post.png"><img
class="alignright size-full wp-image-1149" title="grab-first-image-from-a-post" src="http://www.intechgrity.com/wp-content/uploads/2012/05/grab-first-image-from-a-post.png" alt="" width="300" height="300" /></a>So this the last (perhaps) continuation of the posts <a
title="How to get the souce URL of the featured image in WordPress" href="http://www.intechgrity.com/how-to-get-the-souce-url-of-the-featured-image-in-wordpress/">getting the source URL of the featured image</a> and <a
title="WordPress Multisite compatibility for timthumb" href="http://www.intechgrity.com/wordpress-multisite-compatibility-for-timthumb/">using TimThumb with WordPress MultiSite</a>. As the title says, today we are going to discuss how to automatically fetch the URL of the first image for any WordPress posts or pages and then we shall also see how to pass it to timthumb etc for creating thumbnails. This becomes useful, when your theme/plugin users are not using the <a
title="Setting Post Thumbnail on WordPress with custom size and Cropping – A simpler approach" href="http://www.intechgrity.com/setting-post-thumbnail-on-wordpress-with-custom-size-and-cropping-a-simpler-approach/">featured image</a> thingy of WordPress. In that scenario, what we can do is, search the post content for the any instance of image and return the first found image SRC. In case no images were found, we can also return some default image if necessary. So, let us see what we can do.</p><h2>#1: Understanding the concept:</h2><p>The concept remains the same as our previous post on getting the image SRC of featured image.</p><ul><li>We search the post content using preg_match.</li><li>If any instance is found we return the src.</li><li>Else we return false or optionally return the default image URL</li></ul><h2>#2: The code behind:</h2><pre class="brush: php; title: ; notranslate">
/**
 * Auto Generate Thumbnail URL from the post content
 *
 * First checks if the featured image is present on the post/page or not
 * If yes, then it returns the featured image URL (Source URL)
 * else, it manually searches the content and returns the URL of the first image found
 *
 * If no image is found then it returns the $default variable which is set to false by default
 *
 * @uses itg_get_the_post_thumbnail_url
 * @param int $id Use null if within the loop or give some ID
 * @param string $size The size of the thumbnail, 'post-thumbnail' by default
 * @param bool|string $default The default URL of not-found image or boolean false which will be returned
 * @param string $type The type of the entry. Can be 'post' or 'page'
 * @return mixed bool|string The URL of the featured image or first found image on success, false or default image (as passed by the $default parameter) URL on failure
 */
function itg_auto_gen_thumbnail($id = null, $size = 'post-thumbnail', $default = false, $type = 'post') {
    /**
     * try to get the featured image URL
     * @see http://www.intechgrity.com/how-to-get-the-souce-url-of-the-featured-image-in-wordpress/
     */
    $image_src = itg_get_the_post_thumbnail_url($id, $size);
    if($image_src != '') {
        //on success return the featured image
        return $image_src;
    } else {
        //try to get the first image
        if($id == null) {
            //called within the loop
            $content = get_the_content();
        } else {
            //get the post content
            $p_data = ($type == 'post')? get_post($id) : get_page($id);
            $content = $p_data-&gt;post_content;
            unset($p_data);
        }
        //the match pattern
        $src_pattern = '/&lt;img.+src=[\'&quot;]([^\'&quot;]+)[\'&quot;].*&gt;/i';
        //store $default to $src for returning
        $src = $default;
        $matches = array();

        //match it
        if(preg_match($src_pattern, $content, $matches)) {
            //found, so replace the $src value
            $src = trim($matches[1]);
        }

        return $src;
    }
}
</pre><p>So it is pretty much straight forward. It tries to get the featured image first. If not found then, it searches the content for an image. You call it like this:</p><pre class="brush: php; title: ; notranslate">
//within loop
echo itg_auto_gen_thumbnail();

//within loop for different size
$my_image = itg_auto_gen_thumbnail(null, 'full');

//outside loop for a page
$my_image = itg_auto_gen_thumbnail(10, 'full', false, 'page');

//set default image SRC to return
$my_image = itg_auto_gen_thumbnail(null, 'full', 'http://locati.on/to/image.png');
</pre><p>As you can see, it uses the <span
class="code">itg_get_the_post_thumbnail_url</span> function internally. Have a look at <a
title="How to get the souce URL of the featured image in WordPress" href="http://www.intechgrity.com/how-to-get-the-souce-url-of-the-featured-image-in-wordpress/">here</a> for more information. You can even pass the return image to TimThumb using our <a
title="WordPress Multisite compatibility for timthumb" href="http://www.intechgrity.com/wordpress-multisite-compatibility-for-timthumb/">TimThumb compatibility</a> function for dynamic resizing.</p><p>That will be all. Hope it helps you out for your code. If you have any question, then do ask.</p><p>Related posts:<ol><li><a
href='http://www.intechgrity.com/how-to-get-the-souce-url-of-the-featured-image-in-wordpress/' rel='bookmark' title='How to get the souce URL of the featured image in WordPress'>How to get the souce URL of the featured image in WordPress</a></li><li><a
href='http://www.intechgrity.com/setting-post-thumbnail-on-wordpress-with-custom-size-and-cropping-a-simpler-approach/' rel='bookmark' title='Setting Post Thumbnail on WordPress with custom size and Cropping &#8211; A simpler approach'>Setting Post Thumbnail on WordPress with custom size and Cropping &#8211; A simpler approach</a></li><li><a
href='http://www.intechgrity.com/getting-post-thumbnail-on-wordpress-3-w-wo-specific-post-id/' rel='bookmark' title='Getting Post thumbnail on WordPress 3 w/ w/o specific Post ID'>Getting Post thumbnail on WordPress 3 w/ w/o specific Post ID</a></li><li><a
href='http://www.intechgrity.com/wordpress-multisite-compatibility-for-timthumb/' rel='bookmark' title='WordPress Multisite compatibility for timthumb'>WordPress Multisite compatibility for timthumb</a></li><li><a
href='http://www.intechgrity.com/get-post-count-of-a-category-including-sub-categories-in-wordpress/' rel='bookmark' title='Get post count of a category including sub-categories in WordPress'>Get post count of a category including sub-categories in WordPress</a></li></ol></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p>]]></content:encoded> <wfw:commentRss>http://www.intechgrity.com/catch-the-first-image-on-wordpress-post-and-use-as-thumbnail/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Howto: Choose the right web hosting company for your business</title><link>http://www.intechgrity.com/howto-choose-the-right-web-hosting-company-for-your-business/</link> <comments>http://www.intechgrity.com/howto-choose-the-right-web-hosting-company-for-your-business/#comments</comments> <pubDate>Tue, 15 May 2012 10:43:41 +0000</pubDate> <dc:creator>Swashata</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[Webhosts n Domains]]></category> <category><![CDATA[Web Hosting]]></category><guid isPermaLink="false">http://www.intechgrity.com/?p=1072</guid> <description><![CDATA[<p><p>Original post published <a
href="<a href="http://www.intechgrity.com/howto-choose-the-right-web-hosting-company-for-your-business/">Howto: Choose the right web hosting company for your business</a>">here</a></p><p>We have discussed a lot about web hosting and domains previously. One of the most important thing to consider while buying any web host is, undoubtedly, the value for money. Everyone wants to choose the right web hosting company for his/her business. Now, this is easy to say than to actually compare. With so many [...]</p></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p> Related posts:<ol><li><a
href='http://www.intechgrity.com/use-pickaweb-domain-hosting-to-buy/' rel='bookmark' title='Use PickaWeb Domain Hosting to buy Domains and Web Host at reasonable price'>Use PickaWeb Domain Hosting to buy Domains and Web Host at reasonable price</a></li><li><a
href='http://www.intechgrity.com/choose-best-web-host-for-you-using/' rel='bookmark' title='Choose the Best Web Host for you using WebHostingGeeks.com'>Choose the Best Web Host for you using WebHostingGeeks.com</a></li><li><a
href='http://www.intechgrity.com/choose-your-best-webhost-using/' rel='bookmark' title='Choose your Best Webhost using AlreadyHosting.com ~ One of the best webhosting review provider'>Choose your Best Webhost using AlreadyHosting.com ~ One of the best webhosting review provider</a></li><li><a
href='http://www.intechgrity.com/best-and-affordable-alternatives-of/' rel='bookmark' title='The best and affordable alternatives of Google Page Hosting'>The best and affordable alternatives of Google Page Hosting</a></li><li><a
href='http://www.intechgrity.com/host-your-website-using-one-of-uks-top/' rel='bookmark' title='Host your Website using one of UK’s top WebHosting sites-JustHost [review]'>Host your Website using one of UK’s top WebHosting sites-JustHost [review]</a></li></ol>]]></description> <content:encoded><![CDATA[<p>Original post published <a
href="<a href="http://www.intechgrity.com/howto-choose-the-right-web-hosting-company-for-your-business/">Howto: Choose the right web hosting company for your business</a>">here</a></p><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/webhosting.png"><img
class="alignright  wp-image-1081" title="webhosting" src="http://www.intechgrity.com/wp-content/uploads/2012/05/webhosting.png" alt="" width="250" height="250" /></a>We have discussed a lot about <a
href="http://www.intechgrity.com/category/internet/webhosts-n-domains/">web hosting and domains</a> previously. One of the most important thing to consider while buying any web host is, undoubtedly, the <em>value for money</em>. Everyone wants to choose the right web hosting company for his/her business. Now, this is easy to say than to actually compare. With so many parameters of a reliable web host, so many features of a good web server, it just becomes difficult to choose among the &#8220;best&#8221;s. Luckily, there are services in the Internet which makes our job a lot easier. By looking into comparison tables, reading expert reviews and statistical analysis, going through highlighted features, we can get a better idea before putting money behind a web host. But still, you should have the basic (and well a little advanced won&#8217;t hurt) idea of today&#8217;s server technologies and cost for a profitable long term investment. So, we are going to discuss, what you need to consider before buying any web host. We shall also see some of the reviewing websites from where we can get aggregated information.</p><h2>Things to consider before buying:</h2><p>Out of my own experiences, I think, one should consider the following constrains while buying any web host:</p><h3><strong>#1: Offer Price &amp; Renewal Price:</strong></h3><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/offer-price-renewal-price.png"><img
class="aligncenter size-full wp-image-1077" title="offer-price-renewal-price" src="http://www.intechgrity.com/wp-content/uploads/2012/05/offer-price-renewal-price.png" alt="" width="550" height="150" /></a></p><p>The first thing that should come into mind is, indeed the money. After all you are investing something for your company, so you want to be sure that you get the maximum out of it! Most web hosting services out there offers very less price while buying, and then the renewal price becomes higher. Mostly people overlook this thing. We buy using some promo code and then after a year or two, when the renewal time comes, we have to spend rather a lot to continue the service.<strong></strong></p><h3><strong>#2: Specifications &amp; Features:</strong></h3><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/specifications-features.png"><img
class="aligncenter size-full wp-image-1079" title="specifications-features" src="http://www.intechgrity.com/wp-content/uploads/2012/05/specifications-features.png" alt="" width="550" height="150" /></a></p><p>The most concerned features and specs are, perhaps, diskspace, bandwidth and number of addon domains. The more number of addon domains you have, more number of sites you can host. So, you know that you not just put money behind a single website hosting, rather a multi website hosting. Now a days, most good web hosts give unlimited addon domains.</p><ul><li><strong>Technical Limitations:</strong> Apart from the unlimited stuffs, you should look into the technical limitations. Some host might give you unlimited bandwidth at the cost of limited domains and vice versa. Just keep in mind, what do you really need from your host.</li><li><strong>Domains, Addon Domains, Parked Domains &amp; Sub domains:</strong> The main domain is the domain which is registered primarily with your web host. The addon domains are other domains which you can add and host using the same web host. The parked domains are &#8220;parked&#8221; on some directory of your existing sites. If someone enters the URL of the parked domain, then it will show that directory (and the index file if present). Now sub domains are the children of your main domain. Say, you have<em> mydomain.com</em> as your main domain or addon domain. Then, <em>mysubdomain.mydomain.com</em> would be a sub domain. Now a days, no limits are imposed on all these, which means, with a good web host, you can host unlimited domains with unlimited sub-domains.</li><li><strong>Domain portability: </strong>Another thing you look into is, domain portability. Some hosts out there force you to register your domain with them. Personally, I don&#8217;t prefer to do business with such web hosting companies. What if I want to move my sites to another host? Web hosts which gives the flexibility to add your already registered domain via the name servers, are always my first preferences.</li><li><strong>Bandwidth:</strong> The bigger the value, more visitors your webhost can support. With unlimited bandwidth, this is not an issue in shared hosting. But if you are going for VPS or VPN or Cloud, then you should look into the bandwidth and consider it seriously with respect to the number of visitors in your site. An average site, with around 1500-2000 page visits per day, might consume upto 100GB per month, depending on the data provided by the site. (This figure is mainly for image heavy sites, a text heavy site will actually consume much less bandwidth). You can use tools like <a
href="http://getfirebug.com/" target="_blank">Firebug</a> to check out the size of your pages and estimate average bandwidth by multiplying it with your daily average page visits.</li><li><strong>Disk Usage: </strong>Larger value indicates bigger possibilities for storing audio, video and image files. But also keep in mind that a nice disk usage limitation is useless without a nicer Bandwidth cap. So choose wisely. You won&#8217;t want to have a web host with 100 GB diskspace yet only 10 GB bandwidth per month.</li><li><strong>Server Technology: </strong>The technology depends explicitly on your requirement. If you want to publish a .net or aspx site, then you would prefer <em>Windows Hosting</em>. Where as, if you are familiar with Open source technologies like PHP, MySQL etc, then <em>Linux Hosting</em> should be your first choice. Some of you might want to have several other technologies like <em>Ruby on Rails, Perl, CGI</em> etc.</li><li><strong>Website builder and Auto Installer script:</strong> Now, not everyone of us buy a webhost to create their sites from scratch or install CMS at their own. There are services like <a
href="http://www.softaculous.com/" target="_blank">softaculous</a>, <a
href="https://netenberg.com/fantastico.php" target="_blank">fantastico</a> etc which makes our job even easier. They provide a one click installer for popular CMS like WordPress, Joomla etc. All of the good web hosts should provide atleast one of these auto-installer scripts.</li><li><strong>Emails &amp; Accounts:</strong> If you want to access your email directly within your host, this should be your concern. Personally, I prefer using <a
title="Register your Domain with Google Apps – Beginners Tutorial on setting up the DNS part and URL forwarding" href="http://www.intechgrity.com/register-your-domain-with-google-apps/">google apps to setup my email accounts</a> for the domain. But this feature should not be overlooked.</li><li><strong>SSH Access: </strong>If you know what this feature is, then you probably want your web host to support your feature. For those, who doesn&#8217;t know, <a
href="http://support.hostgator.com/articles/hosting-guide/lets-get-started/how-do-i-get-and-use-ssh-access" target="_blank">here</a> <a
href="http://support.suso.com/supki/SSH_Tutorial_for_Linux" target="_blank">are</a> <a
href="http://wtfh4x.wordpress.com/2010/11/27/25-useful-ssh-commands/" target="_blank">some</a> articles I found from the google explaining the importance and advantages of this feature. Note that for average usage, you won&#8217;t need this.</li></ul><h3><strong>#3: Server Performance &amp; Uptime:</strong></h3><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/serveruptime.png"><img
class="aligncenter size-full wp-image-1078" title="serveruptime" src="http://www.intechgrity.com/wp-content/uploads/2012/05/serveruptime.png" alt="" width="550" height="150" /></a></p><p>You don&#8217;t want your website to be down. There are already services which does the job for us. But in most of the times the information provided is bloated with just too many details. The thing which one should look while choosing a good web host, is, the average uptime for the target region. Which means, if your target visitors are from US, then obviously you should not come into any conclusion from the UK&#8217;s uptime.</p><h3>#4: Technical Support:</h3><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/technical-support.png"><img
class="aligncenter size-full wp-image-1080" title="technical-support" src="http://www.intechgrity.com/wp-content/uploads/2012/05/technical-support.png" alt="" width="550" height="150" /></a></p><p>The next most important thing, is perhaps, how much support and technical help your web host can give. Mostly, now a days, big web hosting companies like Hostgator, Fatcow, BlueHost etc, have their dedicated support forum for their customers. Also, they give 24X7 toll free numbers where you can call and easily get help, regardless of your location. So, you should consider this aspect as well. If your site goes down, then there should be someone to recover.</p><h3>#5: Compliance:</h3><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/compliance.png"><img
class="aligncenter size-full wp-image-1076" title="compliance" src="http://www.intechgrity.com/wp-content/uploads/2012/05/compliance.png" alt="" width="550" height="150" /></a></p><p>When you are using any external web host to host your site, then you should be aware of a few things. Because after all, it is your web host who is finally showing your site to the world. I would recommend to go through it at least once, before buying any web host. It is generally found at their Policy.</p><h2>Doing your own researches:</h2><p>Recently I was looking into fatcow and bluehost reviews in the internet. As an experienced blogger and developer, I am already aware of these two web hosting services and I used to think bluehost is any day better than its competitors because, it has spend more time in the business. But, surprisingly, my concepts changed as soon as I looked into those reviews. Here are the few of the points I noticed:</p><ul><li><a
href="http://www.webhostingsearch.com/review/fatcow" target="_blank">Fatcow will give a 24 months plan at only $3.67/month</a> (at the time of the review). Now that&#8217;s quite a lot of saving. Whereas, for BlueHost it is $19.95/month (although it is for reseller plan, but I prefer to stick to normal plans).</li><li>For <a
href="http://www.webhostingsearch.com/review/bluehost" target="_blank">bluehost, it is $19.94/month for reseller plan</a>. I could not found any offer on normal plans. They have 100GB diskspace, 15Mbps bandwidth, unlimited accounts, but they did not provide any easy to get information on bandwidth cap.</li><li>Fatcow gives free domain &amp; setup along with 75$ marketing credits. Also, just like bluehost it has unlimited addon domains along with unlimited diskspace and bandwidth.</li><li>User recommendation of Fatcows beats BlueHost by 35%. For big web hosting companies like this, 35% is really something to consider.</li></ul><p>So, from all these points, I could figure out that, had I wanted a reseller web host, I would have chosen BlueHost, but, as my needs are limited, so FatCow gives the best solution for me at a very reasonable, rather cheap price.</p><p>I hope you have found this review useful, and it will help you find the best web hosting for you. If you have any doubt, feel free to comment. I will be more than happy to help you.</p><p>Related posts:<ol><li><a
href='http://www.intechgrity.com/use-pickaweb-domain-hosting-to-buy/' rel='bookmark' title='Use PickaWeb Domain Hosting to buy Domains and Web Host at reasonable price'>Use PickaWeb Domain Hosting to buy Domains and Web Host at reasonable price</a></li><li><a
href='http://www.intechgrity.com/choose-best-web-host-for-you-using/' rel='bookmark' title='Choose the Best Web Host for you using WebHostingGeeks.com'>Choose the Best Web Host for you using WebHostingGeeks.com</a></li><li><a
href='http://www.intechgrity.com/choose-your-best-webhost-using/' rel='bookmark' title='Choose your Best Webhost using AlreadyHosting.com ~ One of the best webhosting review provider'>Choose your Best Webhost using AlreadyHosting.com ~ One of the best webhosting review provider</a></li><li><a
href='http://www.intechgrity.com/best-and-affordable-alternatives-of/' rel='bookmark' title='The best and affordable alternatives of Google Page Hosting'>The best and affordable alternatives of Google Page Hosting</a></li><li><a
href='http://www.intechgrity.com/host-your-website-using-one-of-uks-top/' rel='bookmark' title='Host your Website using one of UK’s top WebHosting sites-JustHost [review]'>Host your Website using one of UK’s top WebHosting sites-JustHost [review]</a></li></ol></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p>]]></content:encoded> <wfw:commentRss>http://www.intechgrity.com/howto-choose-the-right-web-hosting-company-for-your-business/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Login, Logout and Administrate using PHP SESSION, COOKIE &amp; MySQL – Version 2 with remember me option</title><link>http://www.intechgrity.com/login-logout-and-administrate-using-php-session-cookie-mysql-version-2-with-remember-me-option/</link> <comments>http://www.intechgrity.com/login-logout-and-administrate-using-php-session-cookie-mysql-version-2-with-remember-me-option/#comments</comments> <pubDate>Fri, 11 May 2012 18:49:05 +0000</pubDate> <dc:creator>Swashata</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[mysql]]></category> <category><![CDATA[php]]></category> <category><![CDATA[php-cookie]]></category> <category><![CDATA[php-post]]></category> <category><![CDATA[php-session]]></category><guid isPermaLink="false">http://www.intechgrity.com/?p=1052</guid> <description><![CDATA[<p><p>Original post published <a
href="<a href="http://www.intechgrity.com/login-logout-and-administrate-using-php-session-cookie-mysql-version-2-with-remember-me-option/">Login, Logout and Administrate using PHP SESSION, COOKIE &#038; MySQL &#8211; Version 2 with remember me option</a>">here</a></p><p>So, our last post on creating login admin and logout seems to be pretty backdated. We decided to come up with a new post under the same topic. So, to start with, let us see what you will be able to do after following this tutorial: Create a MySQL database for managing admin users. Use [...]</p></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p> Related posts:<ol><li><a
href='http://www.intechgrity.com/create-login-admin-logout-page-in-php-w/' rel='bookmark' title='Create Login Admin &amp; Logout Page in PHP w/ SESSION n MySQL'>Create Login Admin &amp; Logout Page in PHP w/ SESSION n MySQL</a></li><li><a
href='http://www.intechgrity.com/get-parent-directory-of-current-url/' rel='bookmark' title='Get Parent directory of Current URL using PHP dirname function'>Get Parent directory of Current URL using PHP dirname function</a></li><li><a
href='http://www.intechgrity.com/how-to-connect-to-xamppmysql-using/' rel='bookmark' title='How to Connect to XAMPP/MySQL using Windows CMD [Command Prompt]'>How to Connect to XAMPP/MySQL using Windows CMD [Command Prompt]</a></li><li><a
href='http://www.intechgrity.com/jquery-recent-post-widget-for/' rel='bookmark' title='jQuery Recent Post Widget for BlogSpot/Blogger with Filter by Tag Option'>jQuery Recent Post Widget for BlogSpot/Blogger with Filter by Tag Option</a></li><li><a
href='http://www.intechgrity.com/understanding-the-basic-of-html-form-and-php-get-and-post-method/' rel='bookmark' title='Understanding the basic of HTML form and PHP GET and POST method'>Understanding the basic of HTML form and PHP GET and POST method</a></li></ol>]]></description> <content:encoded><![CDATA[<p>Original post published <a
href="<a href="http://www.intechgrity.com/login-logout-and-administrate-using-php-session-cookie-mysql-version-2-with-remember-me-option/">Login, Logout and Administrate using PHP SESSION, COOKIE &#038; MySQL &#8211; Version 2 with remember me option</a>">here</a></p><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/secured-login3.png"><img
class="alignright size-medium wp-image-1057" title="secured login[3]" src="http://www.intechgrity.com/wp-content/uploads/2012/05/secured-login3-300x168.png" alt="" width="300" height="168" /></a>So, our last post on <a
title="Create Login Admin &amp; Logout Page in PHP w/ SESSION n MySQL" href="http://www.intechgrity.com/create-login-admin-logout-page-in-php-w/" target="_blank">creating login admin and logout</a> seems to be pretty backdated. We decided to come up with a new post under the same topic. So, to start with, let us see what you will be able to do after following this tutorial:</p><ul><li>Create a MySQL database for managing admin users. Use SHA1 encryption method to store the password in database. Also insert data into it.</li><li>Create your own login/logout system in PHP using Cookie and Session along with remember me option. We shall md5 the SHA1 password in cookie for better protection.</li><li>Understand the PHP code behind the scene. How we have stored the encrypted password in the cookie.</li><li>Implementing the whole thing in OOP (Object Oriented Programming).</li></ul><p>In this tutorial we will do only the basic stuffs, there will be no CSS/HTML styling. In our next release, we will provide you a package with HTML5 admin, from where you can download and use it directly in your projects. This tutorial is intended to explain the basic mechanism used in Login Systems and how cookies and sessions work to provide the administrator security. We will discuss the file and directory structure, the database structure, we will see how we&#8217;ve used MySQL in PHP to connect to database and how we actually authenticate the user for a single session or for multiple session (in case the remember me option is selected). Check out below to get the codes straight away if you know how to do this already and just want to get the code.</p><div
class="demo-download lonely"><a
class="download" title="Login Logout System Downloaded 372" href="http://www.intechgrity.com/downloads/13">Download Now</a></div><p>As for the so called licensing stuffs, this whole thing is just <strong>FREE</strong>. You download, fork, modify, redistribute, use in your project, or do whatever you want. Although a credit will be appreciated, but in this open world of internet, it is completely upto you.</p><p>So, let us start with the directory structure and understand which file does what.</p><h2>#0: File and directory structure:</h2><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/file-structure-login-logout.png"><img
class="aligncenter size-full wp-image-1059" title="file-structure-login-logout" src="http://www.intechgrity.com/wp-content/uploads/2012/05/file-structure-login-logout.png" alt="" width="209" height="199" /></a></p><ul><li><strong>directory &#8211; admin: </strong>The root directory of all your admin files. It contains all the classes, login/logout files etc that we need to get the system running.<ul><li><strong>admin-class.php</strong> &#8211; The main library class of the admin. It contains the several library functions that we need for user authentication, password checking etc.</li><li><strong>index.php</strong> &#8211; The main admin file which should be restricted to the logged in administrator only. If not logged in, then this should redirect to the login page.</li><li><strong>login-action.php</strong> &#8211; The action file which processes the user submitted username and password and authenticates on success. On failure, it redirects to the login page.</li><li><strong>login.php</strong> &#8211; The login form where users are asked to enter their username, password etc along with the a nice remember me option.</li><li><strong>logout.php</strong> &#8211; The logout script which should clear the authentication data and send back the user to the login page.</li></ul></li><li><strong>directory &#8211; db:</strong> The root directory for the database connection files. We have used <a
href="http://justinvincent.com/ezsql" target="_blank">ezSQL</a>to code our application. It gives several query abstractions for faster access.<ul><li><strong>db.php </strong>- It includes the library files <strong>ez_sql_core.php </strong>&amp; <strong>ez_sql_mysql.php</strong> and initializes a global variable <strong>$db</strong> for all the database connections. We shall look more about this later.</li><li><strong>ez_sql_core.php</strong> &#8211; The core ez_sql file as downloaded from the link above.</li><li><strong>ez_sql_mysql.php </strong>- The MySQL extension for the ezSQL.</li></ul></li></ul><h2>#1.1: Creating the database:</h2><p>We shall start by creating a new database for our application. If you are on linux and have MySQL installed, just open up terminal and hit <span
class="code">mysql</span> (you need to access with super user privilege if you have not changed the mysql root, <span
class="code">su mysql</span> or <span
class="code">sudo mysql</span>) and enter the following sql queries.</p><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/database-login-logout.png"><img
class="aligncenter size-medium wp-image-1060" title="database-login-logout" src="http://www.intechgrity.com/wp-content/uploads/2012/05/database-login-logout-300x190.png" alt="" width="300" height="190" /></a></p><pre class="brush: sql; title: ; notranslate">
CREATE DATABASE login_test;
USE login_test;

CREATE TABLE `user` (
`id` INT NOT NULL auto_increment,
`username` VARCHAR(50) NOT NULL default '',
`nicename` VARCHAR(255) NOT NULL default '',
`email` VARCHAR(255) NOT NULL default '',
`password` VARCHAR(255) NOT NULL default '',
UNIQUE KEY `user_n` (`username`),
UNIQUE KEY `user_e` (`email`),
    PRIMARY KEY (`id`)
);

INSERT INTO `user` (`username`, `nicename`, `email`, `password`)
VALUES (
'swashata', 'Swashata Ghosh', 'abc@domain.com', SHA1('pass')
);
</pre><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/database-table-login-logout.png"><img
class="aligncenter size-medium wp-image-1061" title="database-table-login-logout" src="http://www.intechgrity.com/wp-content/uploads/2012/05/database-table-login-logout-300x257.png" alt="" width="300" height="257" /></a></p><p>Let us see what it does:</p><ol><li>Creates a database named <span
class="spanlight">login_test</span>.</li><li>Use that database.</li><li>Create a table <span
class="spanlight">user</span> with id, username, nicename, email and password as fields. Set usename and email as unique keys and id as primary key.</li><li> Insert a user named swashata with nicename Swashata Ghosh, email as above and password as pass.</li><li>Note that we have encrypted the password &#8216;<span
class="spanlight">pass</span>&#8216; using the SHA1 encryption method provided my MySQL. In this way our password is stored in encrypted form. But that also means, you will never be able to see it in original form again. So, how do you reset it? Simple, by querying the database directly. Just</li></ol><p>Now, if you run a SELECT * query, then you will see something like this.</p><p>All done, now let us code the PHP backend.</p><h2>#1.2: Connecting the database with PHP: &#8211; db.php</h2><p>Now, we need to connect this database to our script. To do this, we will be using ezSQL as mentioned before. So, inside our db.php file, we place the following code:</p><pre class="brush: php; title: ; notranslate">
&lt;?php
/**
* The db.php file which initiates a connection to the database
* and gives a global $db variable for access
* @author Swashata &lt;swashata@intechgrity.com&gt;
* @uses ezSQL MySQL
*/
/** edit your configuration */
$dbuser = 'db_user';
$dbname = 'db_name';
$dbpassword = 'db_password';
$dbhost = 'localhost';

/** Stop editing from here, else you know what you are doing <img src='http://www.intechgrity.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  */

/** defined the root for the db */
if(!defined('ADMIN_DB_DIR'))
define('ADMIN_DB_DIR', dirname(__FILE__));

require_once ADMIN_DB_DIR . '/ez_sql_core.php';
require_once ADMIN_DB_DIR . '/ez_sql_mysql.php';
global $db;
$db = new ezSQL_mysql($dbuser, $dbpassword, $dbname, $dbhost);
</pre><p>As you can see, it creates a global $db object which connects to the database from the credential above. To use it, we just need to include this file and declare $db as global.</p><h2>#2: Creating the Login form: &#8211; login.php</h2><p>So, we have used a plain and simple login form with valid xhtml markup. You can add your own css to it to make it look better. The things to notice are</p><ul><li>The name and id of the fields should not change.</li><li>The form method should be post and action should be login-action.php.</li></ul><pre class="brush: xml; title: ; notranslate">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
    &lt;head&gt;
        &lt;title&gt;Login to admin&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;form action=&quot;login-action.php&quot; method=&quot;post&quot;&gt;
            &lt;fieldset&gt;
                &lt;legend&gt;Enter Credential&lt;/legend&gt;
                    &lt;p&gt;
                        &lt;label for=&quot;username&quot;&gt;Username: &lt;/label&gt;
                        &lt;input type=&quot;text&quot; name=&quot;username&quot; id=&quot;username&quot; value=&quot;&quot; /&gt;
                    &lt;/p&gt;
                    &lt;p&gt;
                        &lt;label for=&quot;password&quot;&gt;Password: &lt;/label&gt;
                        &lt;input type=&quot;password&quot; name=&quot;password&quot; id=&quot;password&quot; value=&quot;&quot; /&gt;
                    &lt;/p&gt;
                    &lt;p&gt;
                        &lt;label for=&quot;remember&quot;&gt;
                            &lt;input type=&quot;checkbox&quot; name=&quot;remember&quot; id=&quot;remember&quot; value=&quot;1&quot; /&gt; Remember me
                        &lt;/label&gt;
                    &lt;/p&gt;
            &lt;/fieldset&gt;
            &lt;p&gt;
                &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt; &lt;input type=&quot;reset&quot; value=&quot;Reset&quot; /&gt;
            &lt;/p&gt;
        &lt;/form&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><p>Simple and effective.</p><h2>#3: Creating the library classes &#8211; admin-class.php</h2><p>We first need to analyze what features we need for our library. The basic features are (and also the code behind it):</p><p>#3.0: Initialize the session for login system:</p><p>Login systems work mainly either on session or on cookie. As we are using remember me option, so it is better to use both. Here is how we initialize the session and do some other stuffs.</p><pre class="brush: php; title: ; notranslate">
    /**
     * The constructor function of admin class
     * We do just the session start
     * It is necessary to start the session before actually storing any value
     * to the super global $_SESSION variable
     */
    public function __construct() {
        session_start();

        //store the absolute script directory
        //note that this is not the admin directory
        self::$abs_path = dirname(dirname(__FILE__));

        //initialize the post variable
        if($_SERVER['REQUEST_METHOD'] == 'POST') {
            $this-&gt;post = $_POST;
            if(get_magic_quotes_gpc ()) {
                //get rid of magic quotes and slashes if present
                array_walk_recursive($this-&gt;post, array($this, 'stripslash_gpc'));
            }
        }

        //initialize the get variable
        $this-&gt;get = $_GET;
        //decode the url
        array_walk_recursive($this-&gt;get, array($this, 'urldecode'));
    }
</pre><h3>#3.1: Checking the database for valid username and password combination:</h3><pre class="brush: php; title: ; notranslate">
    /**
     * Check the database for login user
     * Get the password for the user
     * compare md5 hash over sha1
     * @param string $username Raw username
     * @param string $password expected to be md5 over sha1
     * @return bool TRUE on success FALSE otherwise
     */
    private function _check_db($username, $password) {
        global $db;
        $user_row = $db-&gt;get_row(&quot;SELECT * FROM `user` WHERE `username`='&quot; . $db-&gt;escape($username) . &quot;'&quot;);

        //general return
        if(is_object($user_row) &amp;&amp; md5($user_row-&gt;password) == $password)
            return true;
        else
            return false;
    }
</pre><p>So, what we do is, we compare the <span
class="code">md5</span> and <span
class="code">sha1</span> encrypted password with the one stored in database. As the database has only sha1 encrypted password, so we calculate the md5 hash by passing it through the function md5. If it matches, then we return true else, false. You might think, from where we get the username and password. Just keep on reading.</p><h2>#3.2: Add action for the login-action.php file:</h2><pre class="brush: php; title: ; notranslate">
    /**
     * Check for login in the action file
     */
    public function _login_action() {

        //insufficient data provided
        if(!isset($this-&gt;post['username']) || $this-&gt;post['username'] == '' || !isset($this-&gt;post['password']) || $this-&gt;post['password'] == '') {
            header (&quot;location: login.php&quot;);
        }

        //get the username and password
        $username = $this-&gt;post['username'];
        $password = md5(sha1($this-&gt;post['password']));

        //check the database for username
        if($this-&gt;_check_db($username, $password)) {
            //ready to login
            $_SESSION['admin_login'] = $username;

            //check to see if remember, ie if cookie
            if(isset($this-&gt;post['remember'])) {
                //set the cookies for 1 day, ie, 1*24*60*60 secs
                //change it to something like 30*24*60*60 to remember user for 30 days
                setcookie('username', $username, time() + 1*24*60*60);
                setcookie('password', $password, time() + 1*24*60*60);
            } else {
                //destroy any previously set cookie
                setcookie('username', '', time() - 1*24*60*60);
                setcookie('password', '', time() - 1*24*60*60);
            }

            header(&quot;location: index.php&quot;);
        }
        else {
            header (&quot;location: login.php&quot;);
        }

        die();
    }
</pre><p>What it does is, calls the <span
class="code">_check_db</span> function with the username and encrypted password as parameters. If true is returned, then it sets the session for the admin with the username as <span
class="code">$_SESSION['admin_login']</span> variable. Then it further checks for remember me option, and if yes, then it sets cookie as well. We shall discuss more about cookie in some other post. For now, you can just check the comments. As it says, it stores the username and password in the corresponding variables for 1 day. To fetch the cookie we shall use <span
class="code">$_COOKIE</span> super global.</p><h3>#3.3: Creating the authentication method:</h3><pre class="brush: php; title: ; notranslate">
    /**
     * Checks whether the user is authenticated
     * to access the admin page or not.
     *
     * Redirects to the login.php page, if not authenticates
     * otherwise continues to the page
     *
     * @access public
     * @return void
     */
    public function _authenticate() {
        //first check whether session is set or not
        if(!isset($_SESSION['admin_login'])) {
            //check the cookie
            if(isset($_COOKIE['username']) &amp;&amp; isset($_COOKIE['password'])) {
                //cookie found, is it really someone from the
                if($this-&gt;_check_db($_COOKIE['username'], $_COOKIE['password'])) {
                    $_SESSION['admin_login'] = $_COOKIE['username'];
                    header(&quot;location: index.php&quot;);
                    die();
                }
                else {
                    header(&quot;location: login.php&quot;);
                    die();
                }
            }
            else {
                header(&quot;location: login.php&quot;);
                die();
            }
        }
    }
</pre><p>When ever we need to authenticate in a file access, we just have to call this function. We shall see it in the index.php file. It automatically fetches the data from cookie, revalidates it and also redirects to the login.php in case of failure. This is just pretty much what you need.</p><p>#3.4: Putting together the class file &#8211; admin-class.php</p><pre class="brush: php; collapse: true; light: false; title: ; toolbar: true; notranslate">
&lt;?php
/** Include the database file */
include_once '../db/db.php';
/**
 * The main class of login
 * All the necesary system functions are prefixed with _
 * examples, _login_action - to be used in the login-action.php file
 * _authenticate - to be used in every file where admin restriction is to be inherited etc...
 * @author Swashata &lt;swashata@intechgrity.com&gt;
 */
class itg_admin {

    /**
     * Holds the script directory absolute path
     * @staticvar
     */
    static $abs_path;

    /**
     * Store the sanitized and slash escaped value of post variables
     * @var array
     */
    var $post = array();

    /**
     * Stores the sanitized and decoded value of get variables
     * @var array
     */
    var $get = array();

    /**
     * The constructor function of admin class
     * We do just the session start
     * It is necessary to start the session before actually storing any value
     * to the super global $_SESSION variable
     */
    public function __construct() {
        session_start();

        //store the absolute script directory
        //note that this is not the admin directory
        self::$abs_path = dirname(dirname(__FILE__));

        //initialize the post variable
        if($_SERVER['REQUEST_METHOD'] == 'POST') {
            $this-&gt;post = $_POST;
            if(get_magic_quotes_gpc ()) {
                //get rid of magic quotes and slashes if present
                array_walk_recursive($this-&gt;post, array($this, 'stripslash_gpc'));
            }
        }

        //initialize the get variable
        $this-&gt;get = $_GET;
        //decode the url
        array_walk_recursive($this-&gt;get, array($this, 'urldecode'));
    }

    /**
     * Sample function to return the nicename of currently logged in admin
     * @global ezSQL_mysql $db
     * @return string The nice name of the user
     */
    public function get_nicename() {
        $username = $_SESSION['admin_login'];
        global $db;
        $info = $db-&gt;get_row(&quot;SELECT `nicename` FROM `user` WHERE `username` = '&quot; . $db-&gt;escape($username) . &quot;'&quot;);
        if(is_object($info))
            return $info-&gt;nicename;
        else
            return '';
    }

    /**
     * Sample function to return the email of currently logged in admin user
     * @global ezSQL_mysql $db
     * @return string The email of the user
     */
    public function get_email() {
        $username = $_SESSION['admin_login'];
        global $db;
        $info = $db-&gt;get_row(&quot;SELECT `email` FROM `user` WHERE `username` = '&quot; . $db-&gt;escape($username) . &quot;'&quot;);
        if(is_object($info))
            return $info-&gt;email;
        else
            return '';
    }

    /**
     * Checks whether the user is authenticated
     * to access the admin page or not.
     *
     * Redirects to the login.php page, if not authenticates
     * otherwise continues to the page
     *
     * @access public
     * @return void
     */
    public function _authenticate() {
        //first check whether session is set or not
        if(!isset($_SESSION['admin_login'])) {
            //check the cookie
            if(isset($_COOKIE['username']) &amp;&amp; isset($_COOKIE['password'])) {
                //cookie found, is it really someone from the
                if($this-&gt;_check_db($_COOKIE['username'], $_COOKIE['password'])) {
                    $_SESSION['admin_login'] = $_COOKIE['username'];
                    header(&quot;location: index.php&quot;);
                    die();
                }
                else {
                    header(&quot;location: login.php&quot;);
                    die();
                }
            }
            else {
                header(&quot;location: login.php&quot;);
                die();
            }
        }
    }

    /**
     * Check for login in the action file
     */
    public function _login_action() {

        //insufficient data provided
        if(!isset($this-&gt;post['username']) || $this-&gt;post['username'] == '' || !isset($this-&gt;post['password']) || $this-&gt;post['password'] == '') {
            header (&quot;location: login.php&quot;);
        }

        //get the username and password
        $username = $this-&gt;post['username'];
        $password = md5(sha1($this-&gt;post['password']));

        //check the database for username
        if($this-&gt;_check_db($username, $password)) {
            //ready to login
            $_SESSION['admin_login'] = $username;

            //check to see if remember, ie if cookie
            if(isset($this-&gt;post['remember'])) {
                //set the cookies for 1 day, ie, 1*24*60*60 secs
                //change it to something like 30*24*60*60 to remember user for 30 days
                setcookie('username', $username, time() + 1*24*60*60);
                setcookie('password', $password, time() + 1*24*60*60);
            } else {
                //destroy any previously set cookie
                setcookie('username', '', time() - 1*24*60*60);
                setcookie('password', '', time() - 1*24*60*60);
            }

            header(&quot;location: index.php&quot;);
        }
        else {
            header (&quot;location: login.php&quot;);
        }

        die();
    }

    /**
     * Check the database for login user
     * Get the password for the user
     * compare md5 hash over sha1
     * @param string $username Raw username
     * @param string $password expected to be md5 over sha1
     * @return bool TRUE on success FALSE otherwise
     */
    private function _check_db($username, $password) {
        global $db;
        $user_row = $db-&gt;get_row(&quot;SELECT * FROM `user` WHERE `username`='&quot; . $db-&gt;escape($username) . &quot;'&quot;);

        //general return
        if(is_object($user_row) &amp;&amp; md5($user_row-&gt;password) == $password)
            return true;
        else
            return false;
    }

    /**
     * stripslash gpc
     * Strip the slashes from a string added by the magic quote gpc thingy
     * @access protected
     * @param string $value
     */
    private function stripslash_gpc(&amp;$value) {
        $value = stripslashes($value);
    }

    /**
     * htmlspecialcarfy
     * Encodes string's special html characters
     * @access protected
     * @param string $value
     */
    private function htmlspecialcarfy(&amp;$value) {
        $value = htmlspecialchars($value);
    }

    /**
     * URL Decode
     * Decodes a URL Encoded string
     * @access protected
     * @param string $value
     */
    protected function urldecode(&amp;$value) {
        $value = urldecode($value);
    }
}
</pre><h2>#4: Creating the login-action.php file:</h2><p>As we have everything in our class, so creating the login-action.php file will be a breeze. All what we do is</p><ul><li>Include the admin-class.php file.</li><li>Initiate a new instance of the itg_admin class.</li><li>Call the <span
class="code">_login_action</span> function.</li></ul><pre class="brush: php; title: ; notranslate">
&lt;?php
include_once 'admin-class.php';
$admin = new itg_admin();
$admin-&gt;_login_action();
</pre><p>and we are done.</p><h2>#5: Creating the index.php file &#8211; restricted access:</h2><p>So, it is time to put all the codes to work. In index.php file we simply do what we have done in login-action.php file, except of calling the _login_action, we call <span
class="code">_authenticate</span> function. It will automatically check whether user is authenticated to access the further script or not and will redirect to login form if necessary.</p><pre class="brush: php; html-script: true; title: ; notranslate">
&lt;?php
include_once 'admin-class.php';
$admin = new itg_admin();
$admin-&gt;_authenticate();
?&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
    &lt;head&gt;
        &lt;title&gt;Administrator page&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;fieldset&gt;
            &lt;legend&gt;Welcome &lt;?php echo $admin-&gt;get_nicename(); ?&gt;&lt;/legend&gt;
                &lt;p&gt;
                    Here are some of the basic informations
                &lt;/p&gt;
                &lt;p&gt;
                    Username: &lt;?php echo $_SESSION['admin_login']; ?&gt;
                &lt;/p&gt;
                &lt;p&gt;
                    Email: &lt;?php echo $admin-&gt;get_email(); ?&gt;
                &lt;/p&gt;
        &lt;/fieldset&gt;
        &lt;p&gt;
            &lt;input type=&quot;button&quot; onclick=&quot;javascript:window.location.href='logout.php'&quot; value=&quot;logout&quot; /&gt;
        &lt;/p&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><p>and finally&#8230;</p><h2>#6: The logout.php file:</h2><p>Everything seems to be incomplete without it! What we do is</p><ul><li>Destroy the session.</li><li>Expire the cookie.</li><li>Redirect to login form.</li></ul><pre class="brush: php; title: ; notranslate">
&lt;?php
/**
* The logout file
* destroys the session
* expires the cookie
* redirects to login.php
*/
session_start();
session_destroy();
setcookie('username', '', time() - 1*24*60*60);
setcookie('password', '', time() - 1*24*60*60);
header(&quot;location: login.php&quot;);
?&gt;
</pre><p>and we are done. It looks like this</p><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/login-page.png"><img
class="aligncenter size-medium wp-image-1063" title="login-page" src="http://www.intechgrity.com/wp-content/uploads/2012/05/login-page-300x176.png" alt="" width="300" height="176" /></a></p><p><a
href="http://www.intechgrity.com/wp-content/uploads/2012/05/admin-page.png"><img
class="aligncenter size-medium wp-image-1062" title="admin-page" src="http://www.intechgrity.com/wp-content/uploads/2012/05/admin-page-300x173.png" alt="" width="300" height="173" /></a></p><p>So that was all. Feel free to ask any questions you have. I will try best to answer them.</p><p>Related posts:<ol><li><a
href='http://www.intechgrity.com/create-login-admin-logout-page-in-php-w/' rel='bookmark' title='Create Login Admin &amp; Logout Page in PHP w/ SESSION n MySQL'>Create Login Admin &amp; Logout Page in PHP w/ SESSION n MySQL</a></li><li><a
href='http://www.intechgrity.com/get-parent-directory-of-current-url/' rel='bookmark' title='Get Parent directory of Current URL using PHP dirname function'>Get Parent directory of Current URL using PHP dirname function</a></li><li><a
href='http://www.intechgrity.com/how-to-connect-to-xamppmysql-using/' rel='bookmark' title='How to Connect to XAMPP/MySQL using Windows CMD [Command Prompt]'>How to Connect to XAMPP/MySQL using Windows CMD [Command Prompt]</a></li><li><a
href='http://www.intechgrity.com/jquery-recent-post-widget-for/' rel='bookmark' title='jQuery Recent Post Widget for BlogSpot/Blogger with Filter by Tag Option'>jQuery Recent Post Widget for BlogSpot/Blogger with Filter by Tag Option</a></li><li><a
href='http://www.intechgrity.com/understanding-the-basic-of-html-form-and-php-get-and-post-method/' rel='bookmark' title='Understanding the basic of HTML form and PHP GET and POST method'>Understanding the basic of HTML form and PHP GET and POST method</a></li></ol></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p>]]></content:encoded> <wfw:commentRss>http://www.intechgrity.com/login-logout-and-administrate-using-php-session-cookie-mysql-version-2-with-remember-me-option/feed/</wfw:commentRss> <slash:comments>6</slash:comments> </item> <item><title>WP Category Post List version 2 released</title><link>http://www.intechgrity.com/wp-category-post-list-version-2-released/</link> <comments>http://www.intechgrity.com/wp-category-post-list-version-2-released/#comments</comments> <pubDate>Fri, 17 Feb 2012 14:04:46 +0000</pubDate> <dc:creator>Swashata</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[iTg WP Plugin News]]></category> <category><![CDATA[Projects]]></category><guid isPermaLink="false">http://www.intechgrity.com/?p=990</guid> <description><![CDATA[<p><p>Original post published <a
href="<a href="http://www.intechgrity.com/wp-category-post-list-version-2-released/">WP Category Post List version 2 released</a>">here</a></p><p>So after around one year of first release, I finally came up with the 2nd version of the 5 star rated WordPress Category Post List plugin. As you have already guessed, there are plenty of new features in the WP-CPL V2. I have added excerpt option along with shortcode to fulfill everyone&#8217;s need. It is [...]</p></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p> Related posts:<ol><li><a
href='http://www.intechgrity.com/wp-category-post-list-plugin-list-your-posts-filtered-by-categories-with-thumbnails/' rel='bookmark' title='WP Category Post List Plugin &#8211; List your posts filtered by categories with thumbnails'>WP Category Post List Plugin &#8211; List your posts filtered by categories with thumbnails</a></li><li><a
href='http://www.intechgrity.com/setting-post-thumbnail-on-wordpress-with-custom-size-and-cropping-a-simpler-approach/' rel='bookmark' title='Setting Post Thumbnail on WordPress with custom size and Cropping &#8211; A simpler approach'>Setting Post Thumbnail on WordPress with custom size and Cropping &#8211; A simpler approach</a></li><li><a
href='http://www.intechgrity.com/getting-post-thumbnail-on-wordpress-3-w-wo-specific-post-id/' rel='bookmark' title='Getting Post thumbnail on WordPress 3 w/ w/o specific Post ID'>Getting Post thumbnail on WordPress 3 w/ w/o specific Post ID</a></li><li><a
href='http://www.intechgrity.com/safari-web-browser-hits-version-4-new/' rel='bookmark' title='Safari Web browser hits version 4 ~ New Tabs and even Win7 AeroPeek compatibility'>Safari Web browser hits version 4 ~ New Tabs and even Win7 AeroPeek compatibility</a></li><li><a
href='http://www.intechgrity.com/move-intense-debate-comment-from-blogger-to-wordpress-using-export-xml/' rel='bookmark' title='Move Intense Debate Comment from Blogger to WordPress using Export XML ~ First WP plugin by iTg'>Move Intense Debate Comment from Blogger to WordPress using Export XML ~ First WP plugin by iTg</a></li></ol>]]></description> <content:encoded><![CDATA[<p>Original post published <a
href="<a href="http://www.intechgrity.com/wp-category-post-list-version-2-released/">WP Category Post List version 2 released</a>">here</a></p><p
style="text-align: justify;"><a
href="http://www.intechgrity.com/wp-plugins/wp-category-post-list-wordpress-plugin/"><img
class="size-full wp-image-991 aligncenter" title="logo-wp-cpl-v2" src="http://www.intechgrity.com/wp-content/uploads/2012/02/logo-wp-cpl-v2.png" alt="" width="500" height="300" /></a>So after around one year of first release, I finally came up with the 2nd version of the 5 star rated WordPress Category Post List plugin. As you have already guessed, there are plenty of new features in the WP-CPL V2. I have added excerpt option along with shortcode to fulfill everyone&#8217;s need. It is needless to say, the current version is far better than the previous version. Due to hefty amount of added features, I gave it a V2 tag. Some of you might have noticed that version 1.1.0 was there in development trac but it never got released. Finally after compiling a long list of @todo tags, the version 2 is out in the wild.</p><p
style="text-align: justify;"><div
class='et-box et-warning'><div
class='et-box-content'>Version 2.0.2 has been released with bugfix for WP auto upgrade and no css theme selection error. Please upgrade immediately if you are still at version 2.0.0</div></div></p><p>Here are the new features at a glance&#8230;</p><h2>New Features in V2:</h2><ul><li><strong>Shortcode</strong>: The most awaited feature of WP-CPL. Now you can use shortcodes to display a full featured list of category filtered posts</li><li><strong>Multi theme capability</strong>: Unlike version 1, you can add multiple themes to the multiple instances of widgets or shortcodes. For widgets you can simply select the active theme from the dropdown and for shortcodes, you need to enter the id of the css theme.</li><li><strong>More widget configuration</strong>: Added options for displaying <em>author, date</em> etc. Now supports full HTML compatible <strong><em>Read more &amp; Feed </em></strong>anchor.</li><li><strong>Excerpt</strong>: The second most demanding feature. You can now not only show hardcoded excerpts but also can generate length specified excerpts from post contents.</li><li><strong>Auto Detect category</strong>: As requested by many users, the widget now holds an option to automatically detect the current category of the post and list other posts accordingly. If it is homepage or no category is found, the widget output is suspended.</li></ul><h2>Under the hood development:</h2><ul><li>Completely changed the code structure. The whole plugin is now coded in Object Oriented structure.</li><li>Added filters for inserting your own CSS theme to the list. For more check the plugin page.</li><li>Version information now saved via the plugin option. So future upgrade will be smoother.</li><li>Merged widget theme with the shortcode theme. Also tweaked some CSS to make the themes look a bit better.</li><li>Images on the plugin&#8217;s settings page are now loaded locally. We have changed this as per the specification of <a
href="http://wordpress.org/extend/plugins/about/guidelines/">WP Plugin standards</a> (#7).</li></ul><p>That will be all to summarize the release of version 2. Make sure to check the <a
title="WP Category Post List – WordPress Plugin" href="http://www.intechgrity.com/wp-plugins/wp-category-post-list-wordpress-plugin/">documentation page here</a>. Also, you can jump straight to the <a
title="Jump to wordpress extend page" href="http://wordpress.org/extend/plugins/wp-category-posts-list/">WordPress extend page</a> to download and start using this plugin. <strong><em>Don&#8217;t forget to give your feedback</em></strong>.</p><p>Related posts:<ol><li><a
href='http://www.intechgrity.com/wp-category-post-list-plugin-list-your-posts-filtered-by-categories-with-thumbnails/' rel='bookmark' title='WP Category Post List Plugin &#8211; List your posts filtered by categories with thumbnails'>WP Category Post List Plugin &#8211; List your posts filtered by categories with thumbnails</a></li><li><a
href='http://www.intechgrity.com/setting-post-thumbnail-on-wordpress-with-custom-size-and-cropping-a-simpler-approach/' rel='bookmark' title='Setting Post Thumbnail on WordPress with custom size and Cropping &#8211; A simpler approach'>Setting Post Thumbnail on WordPress with custom size and Cropping &#8211; A simpler approach</a></li><li><a
href='http://www.intechgrity.com/getting-post-thumbnail-on-wordpress-3-w-wo-specific-post-id/' rel='bookmark' title='Getting Post thumbnail on WordPress 3 w/ w/o specific Post ID'>Getting Post thumbnail on WordPress 3 w/ w/o specific Post ID</a></li><li><a
href='http://www.intechgrity.com/safari-web-browser-hits-version-4-new/' rel='bookmark' title='Safari Web browser hits version 4 ~ New Tabs and even Win7 AeroPeek compatibility'>Safari Web browser hits version 4 ~ New Tabs and even Win7 AeroPeek compatibility</a></li><li><a
href='http://www.intechgrity.com/move-intense-debate-comment-from-blogger-to-wordpress-using-export-xml/' rel='bookmark' title='Move Intense Debate Comment from Blogger to WordPress using Export XML ~ First WP plugin by iTg'>Move Intense Debate Comment from Blogger to WordPress using Export XML ~ First WP plugin by iTg</a></li></ol></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p>]]></content:encoded> <wfw:commentRss>http://www.intechgrity.com/wp-category-post-list-version-2-released/feed/</wfw:commentRss> <slash:comments>33</slash:comments> </item> <item><title>MySQL: Working with date time arithmetic #Part 2.3.1</title><link>http://www.intechgrity.com/mysql-working-with-date-time-arithmetic-part-2-3-1/</link> <comments>http://www.intechgrity.com/mysql-working-with-date-time-arithmetic-part-2-3-1/#comments</comments> <pubDate>Mon, 19 Dec 2011 13:49:31 +0000</pubDate> <dc:creator>Swashata</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[mysql]]></category> <category><![CDATA[mysql-datetime]]></category><guid isPermaLink="false">http://www.intechgrity.com/?p=942</guid> <description><![CDATA[<p><p>Original post published <a
href="<a href="http://www.intechgrity.com/mysql-working-with-date-time-arithmetic-part-2-3-1/">MySQL: Working with date time arithmetic #Part 2.3.1</a>">here</a></p><p>So, this is the second last part of the long awaited MySQL datetime series. Previously we have leant how to work with MySQL datetime datatypes and how to automate some insertions using some MySQL datetime commands. Obviously the only thing left to discuss is, the (difficult) datetime arithmetic inside MySQL. As in any language, the [...]</p></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p> Related posts:<ol><li><a
href='http://www.intechgrity.com/automatically-insert-current-date-and/' rel='bookmark' title='Automatically insert Current Date and Time in MySQL table #Part – 2.2'>Automatically insert Current Date and Time in MySQL table #Part – 2.2</a></li><li><a
href='http://www.intechgrity.com/mysql-date-and-time-datatypes-overview/' rel='bookmark' title='MySQL date and time DataTypes Overview: DATE, TIME, DATETIME, TIMESTAMP, YEAR &amp; Zero Values #Part2.1'>MySQL date and time DataTypes Overview: DATE, TIME, DATETIME, TIMESTAMP, YEAR &amp; Zero Values #Part2.1</a></li><li><a
href='http://www.intechgrity.com/mysql-datatypes-working-with-fraction-and-decimal-dec/' rel='bookmark' title='MySQL datatypes: working with fraction and decimal [DEC]'>MySQL datatypes: working with fraction and decimal [DEC]</a></li><li><a
href='http://www.intechgrity.com/mysql-data-types-char-varchar-int-text/' rel='bookmark' title='MySQL data types: CHAR, VARCHAR, INT, TEXT #Part-1'>MySQL data types: CHAR, VARCHAR, INT, TEXT #Part-1</a></li><li><a
href='http://www.intechgrity.com/create-login-admin-logout-page-in-php-w/' rel='bookmark' title='Create Login Admin &amp; Logout Page in PHP w/ SESSION n MySQL'>Create Login Admin &amp; Logout Page in PHP w/ SESSION n MySQL</a></li></ol>]]></description> <content:encoded><![CDATA[<p>Original post published <a
href="<a href="http://www.intechgrity.com/mysql-working-with-date-time-arithmetic-part-2-3-1/">MySQL: Working with date time arithmetic #Part 2.3.1</a>">here</a></p><p>So, this is the second last part of the long awaited MySQL datetime series. Previously we have leant how to work with MySQL datetime datatypes and how to automate some insertions using some MySQL datetime commands. Obviously the only thing left to discuss is, the (difficult) datetime arithmetic inside MySQL. As in any language, the datetime arithmetic is not as straight forward as normal arithmetic. The reason is simple, we can&#8217;t say 2+2=4 while dealing with dates <img
src='http://www.intechgrity.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</p><p
style="text-align: center;"><img
class="aligncenter" title="MySQL Datetime Arithmetic" src="http://www.intechgrity.com/wp-content/uploads/2011/12/mysql-datetime-arithmetic.png" alt="" width="500" height="300" /></p><p
style="text-align: justify;">Suppose we have a date, &#8217;2004-02-28&#8242; in YYYY-MM-DD format (which is, a default datetime format for MySQL) and we want to add one more day to the date. So, the result is (supposedly) &#8217;2004-03-01&#8242;. But wait, 2004 is a leap year, so it should be &#8217;2004-02-29&#8242;, right?</p><p
style="text-align: justify;">These are only a few of the difficulties we face while dealing with datetime arithmetic. Luckily, like any efficient programming language, MySQL (although it is a structured query language) has it&#8217;s own set of functions to deal with all these datetime stuffs. Now let us see how we can effectively use those functions to do all our datetime stuffs with queries. But before we start, I would recommend you to go through these two posts related to MySQL:</p><ol><li><a
href="http://www.intechgrity.com/mysql-date-and-time-datatypes-overview/">MySQL date, time and datetime datatype overview</a></li><li><a
href="http://www.intechgrity.com/automatically-insert-current-date-and/">Automatically insert date and time in MySQL tables</a></li></ol><p>Done? Okay, now let us move into further details. In this tutorial we will discuss only the basic and primary arithmetic. In 90% of the cases we will need only these concepts to get our jobs done. Please note that <em>we will show nesting only with default current datetime mysql functions</em>. <em><strong>The nesting is done basically depending on the format of the argument of the main function and format of the return of the nested function</strong></em>.</p><h2>#1: The basic date time arithmetic in MySQL</h2><p>To learn the basic arithmetic calculations, we need to learn three (basically two) date/time functions</p><ul><li>DATE_ADD</li><li>DATE_SUB</li><li>ADDTIME</li><li>SUBTIME</li></ul><h3>#1.1: DATE_ADD &#8211; adds INTERVALS to date:</h3><p><span
class="spanlight">DATE_ADD</span>, as the name suggests, adds specified interval to the provided date. The syntax and usage is given below.</p><h4>Syntax:</h4><pre class="brush: sql; title: ; notranslate">DATE_ADD('YYYY-MM-DD HH:mm:SS', INTERVAL &lt;expr&gt; &lt;UNIT&gt;)</pre><p>So, it passes two arguments.</p><ul><li>The first argument is the <span
class="code">YYYY-MM-DD HH:mm:SS</span> format. We can ignore the <span
class="code">HH:mm:SS</span> and use only <span
class="code">YYYY-MM-DD</span> in case we want only date related calculations.</li><li>The second argument passes the <span
class="code">INTERVAL</span>which is to be added with the proper value. The expressions are<ul><li>expr: The positive or negative integer which to be added to the mentioned date</li><li>UNIT: The unit of the expr. This can be day, month, hour, minute, second and so on. A detailed instruction is found on the table below.</li></ul></li></ul><table
class="css3table"><thead><tr><th
scope="col"> UNIT</th><th
scope="col">EXPR</th><th
scope="col">Example</th></tr></thead><tbody><tr><td> <code>MICROSECOND</code></td><td>Microseconds<code></code></td><td> INTERVAL 100 MICROSECOND</td></tr><tr><td> <code>SECOND</code></td><td>Seconds</td><td> INTERVAL -5 SECOND</td></tr><tr><td> <code>MINUTE</code></td><td>Minutes</td><td> INTERVAL 30 MINUTE</td></tr><tr><td> <code>HOUR</code></td><td>Hours</td><td> INTERVAL 2 HOUR</td></tr><tr><td> <code>DAY</code></td><td>Days</td><td> INTERVAL 5 DAY</td></tr><tr><td> <code>WEEK</code></td><td>Weeks</td><td> INTERVAL 2 WEEK</td></tr><tr><td> <code>MONTH</code></td><td>Months</td><td> INTERVAL 4 MONTH</td></tr><tr><td> <code>YEAR</code></td><td>Years</td><td> INTERVAL 2 YEAR</td></tr></tbody></table><p>Those were only a few. More detailed list of Unit vs Expr can be found <a
href="http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add" target="_blank">here</a>.</p><h4>Nesting:</h4><p>The above function can also be nested with proper <a
title="Automatically insert Current Date and Time in MySQL table #Part – 2.2" href="http://www.intechgrity.com/automatically-insert-current-date-and/" target="_blank">MySQL datetime functions</a>. For example, <span
class="spanlight">CURDATE()</span> or <span
class="spanlight">NOW()</span> can be passed into the first argument.</p><h4>Examples:</h4><p>Here are some direct usage of DATE_ADD using SELECT query:</p><pre class="brush: sql; title: ; notranslate">SELECT DATE_ADD('2004-02-28', INTERVAL 1 DAY) AS leap_year;
SELECT DATE_ADD(CURDATE(), INTERVAL 1 YEAR) AS day_next_year;
SELECT YEAR(DATE_ADD(CURDATE(), INTERVAL 101 YEAR)) AS next_101_year; --Extracts the year from the date_add arithmetic
SELECT DATE_ADD(NOW(), INTERVAL 30 MINUTE) AS time_next_half_hour;</pre><p>The output is shown below</p><div
id="attachment_947" class="wp-caption aligncenter" style="width: 310px"><a
href="http://www.intechgrity.com/wp-content/uploads/2011/12/mysql-date_add-examples1.png"><img
class="size-medium wp-image-947" title="mysql-date_add-examples" src="http://www.intechgrity.com/wp-content/uploads/2011/12/mysql-date_add-examples1-300x204.png" alt="MySQL DATE_ADD Examples" width="300" height="204" /></a><p
class="wp-caption-text">MySQL DATE_ADD Examples</p></div><h3>#1.2: DATE_SUB &#8211; subtracts INTERVAL from date:</h3><p>Theoretically, it does the same job as DATE_ADD with negative interval. So the following codes are similar</p><pre class="brush: sql; title: ; notranslate">--So the code
SELECT DATE_SUB(CURDATE(), INTERVAL 1 DAY);
--is equivalent to
SELECT DATE_ADD(CURDATE(), INTERVAL -1 DAY);</pre><p>It has the same synopsis (syntax) and expressions as <span
class="spanlight">DATE_ADD</span>. The output of the above query is shown below.</p><div
id="attachment_948" class="wp-caption aligncenter" style="width: 310px"><a
href="http://www.intechgrity.com/wp-content/uploads/2011/12/date_add-vs-date_sub-mysql.png"><img
class="size-medium wp-image-948" title="DATE_ADD vs DATE_SUB in MySQL" src="http://www.intechgrity.com/wp-content/uploads/2011/12/date_add-vs-date_sub-mysql-300x156.png" alt="DATE_ADD vs DATE_SUB in MySQL" width="300" height="156" /></a><p
class="wp-caption-text">DATE_ADD vs DATE_SUB in MySQL</p></div><h3> #1.3: ADDTIME() and SUBTIME() to work only with time:</h3><p>As the names suggest, ADDTIME() is used for adding time to a specified time and SUBTIME() is used for subtracting time from a specified time. Here are in depth details.</p><h4>Syntax:</h4><pre class="brush: sql; title: ADDTIME synopsis; notranslate">ADDTIME(&lt;expr1&gt;, &lt;expr2&gt;);</pre><pre class="brush: sql; title: SUBTIME synopsis; notranslate">SUBTIME(&lt;expr1&gt;, &lt;expr2&gt;);</pre><ul><li><strong><em>expr1, expr2 </em></strong>are both in <span
class="code">HH:mm:SS</span> format.</li><li>ADDTIME adds expr2 to expr1 and returns the result.</li><li>SUBTIME subtracts expr2 from expr1 and returns the result.</li></ul><h4>Nesting:</h4><p>This can be nested with time returning functions such as <span
class="spanlight">CURTIME()</span>.</p><h4>Examples:</h4><pre class="brush: sql; title: ; notranslate">SELECT ADDTIME('12:00:01', '00:30:59');
SELECT SUBTIME('12:59:03', '00:09:04');
SELECT ADDTIME(CURTIME(), '14:00:00');</pre><p>The output is shown below</p><div
id="attachment_949" class="wp-caption aligncenter" style="width: 310px"><a
href="http://www.intechgrity.com/wp-content/uploads/2011/12/mysql-addtime-and-subtime.png"><img
class="size-medium wp-image-949" title="MySQL ADDTIME and SUBTIME" src="http://www.intechgrity.com/wp-content/uploads/2011/12/mysql-addtime-and-subtime-300x156.png" alt="MySQL ADDTIME and SUBTIME" width="300" height="156" /></a><p
class="wp-caption-text">MySQL ADDTIME and SUBTIME</p></div><h2> #2: Advance date-time arithmetic functions:</h2><p>Now that we are familiar with the basics, let us now see, some advanced functions which will become handy in real world projects. Here we are going to discuss the following functions</p><ul><li>DATEDIFF</li><li>TIMEDIFF</li><li>LASTDAY</li><li>EXTRACT</li><li>MAKEDATE</li><li>MAKETIME</li></ul><h3>#2.1: DATEDIFF &#8211; calculates days between two dates:</h3><p>The difference between <span
class="spanlight">DATEDIFF</span> and <span
class="spanlight">DATE_SUB</span> is that, <span
class="spanlight">DATEDIFF</span> returns the number of days between two dates. It can be either positive or negative.</p><h4>Syntax:</h4><pre class="brush: sql; title: ; notranslate">DATEDIFF(&lt;expr1&gt;, &lt;expr2&gt;)</pre><ul><li><strong><em>expr1, expr2</em></strong> can be either <span
class="code">YYYY-MM-DD HH:mm:SS</span> or <span
class="code">YYYY-MM-DD</span>. Only <span
class="code">YYYY-MM-DD</span> will be used for the calculation</li><li>It returns <strong><em>expr1 &#8211; expr2</em></strong> in number of <strong>days</strong>.</li></ul><h4>Nesting:</h4><p>Due to the format of the arguments it supports, <span
class="spanlight">CURDATE()</span> and <span
class="spanlight">NOW()</span> can be nested.</p><h4>Example:</h4><pre class="brush: sql; title: ; notranslate">SELECT DATEDIFF('2010-12-31', '2011-01-01');
SELECT DATEDIFF('2011-12-31', '2010-01-01');
SELECT DATEDIFF('2011-12-21', '2011-12-30');
SELECT DATEDIFF(DATE_ADD(CURDATE(), INTERVAL 1 MONTH), CURDATE());</pre><p>The output is</p><div
id="attachment_950" class="wp-caption aligncenter" style="width: 310px"><a
href="http://www.intechgrity.com/wp-content/uploads/2011/12/mysql-datediff.png"><img
class="size-medium wp-image-950" title="MySQL DATEDIFF" src="http://www.intechgrity.com/wp-content/uploads/2011/12/mysql-datediff-300x199.png" alt="MySQL DATEDIFF" width="300" height="199" /></a><p
class="wp-caption-text">Working with MySQL DATEDIFF</p></div><h4 class="faq">Food for thought:</h4><p>Note how the last query can be used to get the number of days in the upcoming month. Now try and think how we can use similar query to get the number of days in upcoming year.</p><div
class='et-learn-more clearfix'><h3 class='heading-more'><span>Want to check the answer?</span></h3><div
class='learn-more-content'><pre class="brush: sql; title: ; notranslate">SELECT DATEDIFF(DATE_ADD(NOW(), INTERVAL 1 YEAR), NOW());</pre><p>CURDATE could also be used, instead of NOW</div></div><h3>#2.2: TIMEDIFF &#8211; calculates HH:mm:SS b/w two times:</h3><p>This is pretty straight forward. It takes two arguments in time format, subtracts and returns the result.</p><h4>Syntax:</h4><pre class="brush: sql; title: ; notranslate">TIMEDIFF(&lt;expr1&gt;, &lt;expr2&gt;)</pre><ul><li><strong><em>expr1, expr2</em></strong> is of the format <span
class="code">HH:mm:SS</span></li><li>It returns <strong><em>expr1 &#8211; expr2</em></strong> as time value in <span
class="code">HH:mm:SS</span> format.</li></ul><h4>Nesting:</h4><p>It can be nested with <span
class="spanlight">CURTIME()</span> function. We will see this in the examples.</p><h4>Examples:</h4><pre class="brush: sql; title: ; notranslate">SELECT TIMEDIFF('24:12:01', '12:12:00');
SELECT TIMEDIFF(CURTIME(), '00:30:00');</pre><p>The output is shown below.</p><div
id="attachment_951" class="wp-caption aligncenter" style="width: 310px"><a
href="http://www.intechgrity.com/wp-content/uploads/2011/12/mysql-timediff.png"><img
class="size-medium wp-image-951" title="Using MySQL TIMEDIFF" src="http://www.intechgrity.com/wp-content/uploads/2011/12/mysql-timediff-300x114.png" alt="Using MySQL TIMEDIFF" width="300" height="114" /></a><p
class="wp-caption-text">Using MySQL TIMEDIFF</p></div><h3>#2.3: LAST_DAY &#8211; of specified month of date:</h3><p>This returns the last day date of the year-month-day passed in the argument.</p><h4>Syntax:</h4><pre class="brush: sql; title: ; notranslate">LAST_DAY(&lt;date&gt;)</pre><ul><li><strong><em>date</em></strong> is the <span
class="code">YYYY-MM-DD</span> value passed.</li><li>It returns a <span
class="code">YYYY-MM-DD</span> which corresponds to the last day of the month of the year.</li></ul><h4>Nesting:</h4><p>As obvious, it can be nested with <span
class="spanlight">CURDATE()</span> function.</p><h4>Examples:</h4><pre class="brush: sql; title: ; notranslate">SELECT LAST_DAY('2012-02-01');
SELECT LAST_DAY(CURDATE());</pre><p>The output is</p><div
id="attachment_952" class="wp-caption aligncenter" style="width: 310px"><a
href="http://www.intechgrity.com/wp-content/uploads/2011/12/mysql-last_day.png"><img
class="size-medium wp-image-952" title="Using MySQL LAST_DAY" src="http://www.intechgrity.com/wp-content/uploads/2011/12/mysql-last_day-300x109.png" alt="Using MySQL LAST_DAY" width="300" height="109" /></a><p
class="wp-caption-text">Using MySQL LAST_DAY</p></div><h3>#2.4: EXTRACT &#8211; what you need from date/time stamp:</h3><p>This allows extracting a specific part of the datetime from the passed argument.</p><h4>Syntax:</h4><pre class="brush: sql; title: ; notranslate">EXTRACT(&lt;unit&gt; FROM &lt;date&gt;)</pre><ul><li>The <em><strong>unit</strong></em> is same as <span
class="spanlight">DATE_ADD()</span>.</li><li>The <strong><em>date </em></strong>can be<ul><li>Complete <span
class="code">YYYY-MM-DD HH:mm:SS</span></li><li>Just <em>date</em> format as <span
class="code">YYYY-MM-DD</span></li><li>Just <em>time</em> format as <span
class="code">HH:mm:SS</span></li></ul></li></ul><p>It returns just the expression for the specified unit.</p><h4>Nesting:</h4><p>Because of the flexibility, it can be nested with all the date time functions as <span
class="spanlight">NOW()</span>, <span
class="spanlight">CURDATE()</span>, <span
class="spanlight">CURTIME()</span> etc.</p><h4>Examples:</h4><pre class="brush: sql; title: ; notranslate">SELECT EXTRACT(MONTH FROM '2011-02-28');
SELECT EXTRACT(DAY FROM LAST_DAY('2012-02-01')); --effective eh?
SELECT EXTRACT(DAY FROM DATE_ADD(CURDATE(), INTERVAL 20 DAY)); --even more complex
SELECT EXTRACT(HOUR FROM CURTIME()); --Works with HH:mm:SS too</pre><p>The outputs are</p><div
id="attachment_953" class="wp-caption aligncenter" style="width: 310px"><a
href="http://www.intechgrity.com/wp-content/uploads/2011/12/using-mysql-extract.png"><img
class="size-medium wp-image-953" title="Using MySQL EXTRACT" src="http://www.intechgrity.com/wp-content/uploads/2011/12/using-mysql-extract-300x199.png" alt="Using MySQL EXTRACT" width="300" height="199" /></a><p
class="wp-caption-text">Using MySQL EXTRACT</p></div><h3>#2.5: MAKEDATE &#8211; from year and day:</h3><p>It constructs a date when the year and day of the year is given.</p><h4>Syntax:</h4><pre class="brush: sql; title: ; notranslate">MAKEDATE(&lt;year&gt;, &lt;day_of_year&gt;)</pre><ul><li>The <strong><em>year</em></strong> is the year of which the date is to be calculated.</li><li>The <strong><em>day_of_year</em></strong> is the count of the day from the beginning.</li><li>It returns a date in <span
class="code">YYYY-MM-DD</span> format.</li></ul><h4>Nesting:</h4><p>Due to the format of the input arguments, it can not be nested directly with any MySQL current datetime functions.</p><h4>Examples:</h4><pre class="brush: sql; title: ; notranslate">SELECT MAKEDATE(2012, 365);
SELECT MAKEDATE(2010, DATEDIFF(CURDATE(), '2011-04-12'));
SELECT MAKEDATE(2000, DATEDIFF(CURDATE(), '2000-01-01'));
SELECT MAKEDATE(2000, DATEDIFF(DATE_ADD(CURDATE(), INTERVAL 1 DAY), '2000-01-01')) AS today;</pre><p>The output is</p><div
id="attachment_954" class="wp-caption aligncenter" style="width: 310px"><a
href="http://www.intechgrity.com/wp-content/uploads/2011/12/mysql-makedate.png"><img
class="size-medium wp-image-954" title="Using MySQL MAKEDATE" src="http://www.intechgrity.com/wp-content/uploads/2011/12/mysql-makedate-300x204.png" alt="Using MySQL MAKEDATE" width="300" height="204" /></a><p
class="wp-caption-text">Using MySQL MAKEDATE</p></div><h4 class="faq">Food for thought:</h4><p>Note how the last query gives today&#8217;s date. Can you think further to give same date for the next year? As in, today&#8217;s date is 2011-12-19. Can you print 2012-12-19 in similar approach?</p><div
class='et-learn-more clearfix'><h3 class='heading-more'><span>Want to check the answer?</span></h3><div
class='learn-more-content'><pre class="brush: sql; title: ; notranslate">SELECT MAKEDATE(2001, DATEDIFF(DATE_ADD(CURDATE(), INTERVAL 1 DAY), '2000-01-01')) AS next_year_today;</pre><p>Easy right? We just took the difference from the same year and constructed from one more year (2001).</div></div><h3>#2.6: MAKETIME &#8211; from HH, mm &amp; SS:</h3><p>This is very simple, yet useful function. It constructs a Time format from the given arguments.</p><h4>Syntax:</h4><pre class="brush: sql; title: ; notranslate">MAKETIME(&lt;hour&gt;, &lt;minute&gt;, &lt;second&gt;)</pre><ul><li>The <em><strong>hour, minute, second</strong></em>arguments can hold only the legal values<ul><li>0-59 for <em><strong>minute, second</strong></em></li></ul></li></ul><p>It returns a nicely formatted <span
class="code">HH:mm:SS</span> value from the arguments.</p><h4>Nesting:</h4><p>Due to it&#8217;s format, it can not be nested with current datetime mysql functions.</p><h4>Examples:</h4><pre class="brush: sql; title: ; notranslate">SELECT MAKETIME(12, 34, 11);
SELECT MAKETIME(12, EXTRACT(MINUTE FROM CURTIME()), 59);</pre><p>The outputs are</p><div
id="attachment_956" class="wp-caption aligncenter" style="width: 310px"><a
href="http://www.intechgrity.com/wp-content/uploads/2011/12/mysql-maketime.png"><img
class="size-medium wp-image-956" title="Using MySQL MAKETIME" src="http://www.intechgrity.com/wp-content/uploads/2011/12/mysql-maketime-300x114.png" alt="Using MySQL MAKETIME" width="300" height="114" /></a><p
class="wp-caption-text">Using MySQL MAKETIME</p></div><p>So that was all. Hope it will help you understand better the concept of MySQL datetime arithmetic. <em>If you have any doubt, just throw in using the comments form</em>. In the next tutorial, we will see how to use these functions in real world using a MySQL table. You can also check the <a
href="http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html" target="_blank">official MySQL documentation</a> for more available datetime functions. Oh, and here is a downloadable SQL file for your ease!</p><div
class="demo-download lonely"><a
class="download" title="MySQL datetime arithmetic functions Downloaded 76" href="http://www.intechgrity.com/downloads/12">Download Now</a></div><p>Related posts:<ol><li><a
href='http://www.intechgrity.com/automatically-insert-current-date-and/' rel='bookmark' title='Automatically insert Current Date and Time in MySQL table #Part – 2.2'>Automatically insert Current Date and Time in MySQL table #Part – 2.2</a></li><li><a
href='http://www.intechgrity.com/mysql-date-and-time-datatypes-overview/' rel='bookmark' title='MySQL date and time DataTypes Overview: DATE, TIME, DATETIME, TIMESTAMP, YEAR &amp; Zero Values #Part2.1'>MySQL date and time DataTypes Overview: DATE, TIME, DATETIME, TIMESTAMP, YEAR &amp; Zero Values #Part2.1</a></li><li><a
href='http://www.intechgrity.com/mysql-datatypes-working-with-fraction-and-decimal-dec/' rel='bookmark' title='MySQL datatypes: working with fraction and decimal [DEC]'>MySQL datatypes: working with fraction and decimal [DEC]</a></li><li><a
href='http://www.intechgrity.com/mysql-data-types-char-varchar-int-text/' rel='bookmark' title='MySQL data types: CHAR, VARCHAR, INT, TEXT #Part-1'>MySQL data types: CHAR, VARCHAR, INT, TEXT #Part-1</a></li><li><a
href='http://www.intechgrity.com/create-login-admin-logout-page-in-php-w/' rel='bookmark' title='Create Login Admin &amp; Logout Page in PHP w/ SESSION n MySQL'>Create Login Admin &amp; Logout Page in PHP w/ SESSION n MySQL</a></li></ol></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p>]]></content:encoded> <wfw:commentRss>http://www.intechgrity.com/mysql-working-with-date-time-arithmetic-part-2-3-1/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>WP Simple Event Management Plugin by iTg – Manage college fests and events</title><link>http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/</link> <comments>http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/#comments</comments> <pubDate>Fri, 17 Sep 2010 09:46:05 +0000</pubDate> <dc:creator>Swashata</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[iTg WP Plugin News]]></category> <category><![CDATA[Projects]]></category> <category><![CDATA[wordpress]]></category> <category><![CDATA[wordpress plugins]]></category><guid isPermaLink="false">http://www.intechgrity.com/?p=762</guid> <description><![CDATA[<p><p>Original post published <a
href="<a href="http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/">WP Simple Event Management Plugin by iTg &#8211; Manage college fests and events</a>">here</a></p><p>So, after a long break, we are back. Back with another cool new WordPress Plugin. The reason behind the in-activeness was I was really busy doing some college work and working for a client. Luckily both of the work progressed well, and the best part is, I successfully developed an Event management plugin for WordPress. [...]</p></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p> Related posts:<ol><li><a
href='http://www.intechgrity.com/move-intense-debate-comment-from-blogger-to-wordpress-using-export-xml/' rel='bookmark' title='Move Intense Debate Comment from Blogger to WordPress using Export XML ~ First WP plugin by iTg'>Move Intense Debate Comment from Blogger to WordPress using Export XML ~ First WP plugin by iTg</a></li><li><a
href='http://www.intechgrity.com/determine-plugin-directory-and-url-in-wordpress-using-wp-api/' rel='bookmark' title='Determine Plugin Directory and URL in WordPress using WP API'>Determine Plugin Directory and URL in WordPress using WP API</a></li><li><a
href='http://www.intechgrity.com/wp-category-post-list-plugin-list-your-posts-filtered-by-categories-with-thumbnails/' rel='bookmark' title='WP Category Post List Plugin &#8211; List your posts filtered by categories with thumbnails'>WP Category Post List Plugin &#8211; List your posts filtered by categories with thumbnails</a></li><li><a
href='http://www.intechgrity.com/how-to-add-your-own-stylesheet-to-your-wordpress-plugin-settings-page-or-all-admin-page/' rel='bookmark' title='How to add your own stylesheet to your WordPress plugin settings page or All Admin page'>How to add your own stylesheet to your WordPress plugin settings page or All Admin page</a></li><li><a
href='http://www.intechgrity.com/jquery-fade-n-slide-button-animator-plugin-by-itg/' rel='bookmark' title='jQuery Fade n Slide Button Animator Plugin by iTg'>jQuery Fade n Slide Button Animator Plugin by iTg</a></li></ol>]]></description> <content:encoded><![CDATA[<p>Original post published <a
href="<a href="http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/">WP Simple Event Management Plugin by iTg &#8211; Manage college fests and events</a>">here</a></p><p><img
class="aligncenter size-full wp-image-778" title="wp simple event management system" src="http://www.intechgrity.com/wp-content/uploads/2010/09/wp-simple-event-management-system.png" alt="" width="500" height="300" />So, after a long break, we are back. Back with another cool new WordPress Plugin. The reason behind the in-activeness was I was really busy doing some college work and working for a client. Luckily both of the work progressed well, and the best part is, I successfully developed an Event management plugin for WordPress. Yes, this plugin has been made open source. Using <strong>WP Simple Event Management</strong> you can easily add events with start date, end date and users [subscribers of wordpress user system] can apply for any upcoming events with their own <strong>Team Members</strong>. Before we start, here is a list of features the plugin has:</p><h2>#0: What the plugin Does:</h2><p>It basically extends WordPress&#8217; user system and admin panel to equipt your site with event management system. It adds two main menus to the WordPress Admin panel menu:</p><ul><li><strong>Events Admin</strong> -  <a
href="http://www.intechgrity.com/wp-content/uploads/2010/09/Events-Admin-Menu.png"><img
class="aligncenter size-full wp-image-769" title="Events Admin Menu" src="http://www.intechgrity.com/wp-content/uploads/2010/09/Events-Admin-Menu.png" alt="" width="156" height="254" /></a>A place from where Administrators and Editors can add/edit events and manage attendees.</li><li><strong>Events Info</strong>. &#8211; <a
href="http://www.intechgrity.com/wp-content/uploads/2010/09/Events-Info-User-menu.png"><img
class="aligncenter size-full wp-image-770" title="Events Info User menu" src="http://www.intechgrity.com/wp-content/uploads/2010/09/Events-Info-User-menu.png" alt="" width="149" height="165" /></a>A place from where all the users can apply for events, add team members, check application status, update contact information etc.</li></ul><p>The plugin was developed mainly for <em><strong>college/university/school</strong></em> event management. So, it supports all academic details one needs to enter to uniquely identify him/her. Also, while administrating events, you can set price, discount, event description, venue and much more. Just use this plugin to know how.</p><h2>#1: Download The plugin:</h2><p>It can be downloaded from WordPress repository. Every instruction is given there:</p><div
class="demo-download lonely"><a
class="download" href="http://wordpress.org/extend/plugins/wp-simple-event-management-system/">Download</a></div><h2>#2: Video Tutorials:</h2><p>There are two video tutorials as of now. One tells you how to use the admin section, and other how to register and apply for events.</p><p><strong>Admin Interface</strong><br
/> <object
classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="500" height="315" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param
name="allowFullScreen" value="true" /><param
name="allowscriptaccess" value="always" /><param
name="src" value="http://www.youtube.com/v/zDKE9U0EWQQ?fs=1&amp;hl=en_US&amp;color1=0x234900&amp;color2=0x4e9e00&amp;border=1" /><param
name="allowfullscreen" value="true" /><embed
type="application/x-shockwave-flash" width="500" height="315" src="http://www.youtube.com/v/zDKE9U0EWQQ?fs=1&amp;hl=en_US&amp;color1=0x234900&amp;color2=0x4e9e00&amp;border=1" allowscriptaccess="always" allowfullscreen="true"></embed></object></p><p><strong>User Interface: </strong><br
/> <object
classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="500" height="315" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param
name="allowFullScreen" value="true" /><param
name="allowscriptaccess" value="always" /><param
name="src" value="http://www.youtube.com/v/BMWdZQg4X8A?fs=1&amp;hl=en_US&amp;color1=0x234900&amp;color2=0x4e9e00&amp;border=1" /><param
name="allowfullscreen" value="true" /><embed
type="application/x-shockwave-flash" width="500" height="315" src="http://www.youtube.com/v/BMWdZQg4X8A?fs=1&amp;hl=en_US&amp;color1=0x234900&amp;color2=0x4e9e00&amp;border=1" allowscriptaccess="always" allowfullscreen="true"></embed></object></p><h2>#3: Feature List:</h2><ul><li>User are required to register to your site for applying and managing  their events. User registration is fully integrated with WP. If the  plugin is activated, then if you delete any user from WP panel, then it  will also delete his/her team members, profile, applications if present  in the plugins database.</li><li>Admin can add/edit any number of events with start/end date, fully HTML enabled Description and Venue field.</li><li>User can apply for any number of events.</li><li>Prices can be set or a particular event can be made FREE, or Announced Later. <img
src='http://www.intechgrity.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /></li><li>Generation of Unique Registration ID for every application.</li><li>User can add any number of additional team members</li><li>For a particular event admin can restrict the team members to  whatever number and also can make the team members optional or  mandatory. User will be prompted accordingly.</li><li>User can check status of their application.</li><li>Admin can approve user application.</li><li>When user apply for an event admin gets mailed. Here the &#8220;to&#8221; email will be the one inserted in the <strong>Instutition Information</strong> &gt; <em>contact email</em> part</li><li>Complete option to enter institution name and contact information for the admin</li><li>User must enter phone number, optionally inst. name, address etc.  His email and name is integrated with the wordpress account. User can  apply for events only after complete profile update.</li><li>Admin has complete control over everything.</li><li>Any user type can apply for an event. Whereas only admin and editor can manage events.</li><li>Event detail, Member Detail, Application Status etc all are fetched  via AJAX over a jQuery thickbox, which gives user a cool interface.</li><li>Administrator can print all the registration within a specified date  range. It will give the registration table grouped by applicants.</li><li>Usage of rich jQuery UI for the general applicant&#8217;s interface.</li></ul><h2>#4: Documentation:</h2><p><em>Coming soon&#8230;</em> Please check the video tutorials as of now</p><h2>#5: Gallery:</h2><p>Below are some screenshots which you can see to get an idea about how the whole thing works.</p><a
href='http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/wp-simple-event-management-system/' title='wp simple event management system'><img
width="150" height="150" src="http://www.intechgrity.com/wp-content/uploads/2010/09/wp-simple-event-management-system-150x150.png" class="attachment-thumbnail" alt="wp simple event management system" title="wp simple event management system" /></a> <a
href='http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/events-admin-menu/' title='Events Admin Menu'><img
width="150" height="150" src="http://www.intechgrity.com/wp-content/uploads/2010/09/Events-Admin-Menu-150x150.png" class="attachment-thumbnail" alt="Events Admin Menu" title="Events Admin Menu" /></a> <a
href='http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/events-info-user-menu/' title='Events Info User menu'><img
width="149" height="150" src="http://www.intechgrity.com/wp-content/uploads/2010/09/Events-Info-User-menu-149x150.png" class="attachment-thumbnail" alt="Events Info User menu" title="Events Info User menu" /></a> <a
href='http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/admin-institution-details/' title='Admin Institution Details'><img
width="150" height="150" src="http://www.intechgrity.com/wp-content/uploads/2010/09/Admin-Institution-Details-150x150.png" class="attachment-thumbnail" alt="Admin Institution Details" title="Admin Institution Details" /></a> <a
href='http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/admin-adding-events/' title='Admin Adding Events'><img
width="150" height="150" src="http://www.intechgrity.com/wp-content/uploads/2010/09/Admin-Adding-Events-150x150.png" class="attachment-thumbnail" alt="Admin Adding Events" title="Admin Adding Events" /></a> <a
href='http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/admin-editing-events/' title='Admin Editing Events'><img
width="150" height="150" src="http://www.intechgrity.com/wp-content/uploads/2010/09/Admin-Editing-Events-150x150.png" class="attachment-thumbnail" alt="Admin Editing Events" title="Admin Editing Events" /></a> <a
href='http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/admin-activa-attendees-and-editing/' title='Admin Active Attendees and editing'><img
width="150" height="150" src="http://www.intechgrity.com/wp-content/uploads/2010/09/Admin-Activa-Attendees-and-editing-150x150.png" class="attachment-thumbnail" alt="Admin Active Attendees and editing" title="Admin Active Attendees and editing" /></a> <a
href='http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/admin-printing-all-the-registration/' title='Admin printing all the registration'><img
width="150" height="150" src="http://www.intechgrity.com/wp-content/uploads/2010/09/Admin-printing-all-the-registration-150x150.png" class="attachment-thumbnail" alt="Admin printing all the registration" title="Admin printing all the registration" /></a> <a
href='http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/admin-viewing-users/' title='Admin Viewing users'><img
width="150" height="150" src="http://www.intechgrity.com/wp-content/uploads/2010/09/Admin-Viewing-users-150x150.png" class="attachment-thumbnail" alt="Admin Viewing users" title="Admin Viewing users" /></a> <a
href='http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/users-help-and-support/' title='Users Help and Support'><img
width="150" height="150" src="http://www.intechgrity.com/wp-content/uploads/2010/09/Users-Help-and-Support-150x150.png" class="attachment-thumbnail" alt="Users Help and Support" title="Users Help and Support" /></a> <a
href='http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/users-contact-information/' title='Users Contact Information'><img
width="150" height="150" src="http://www.intechgrity.com/wp-content/uploads/2010/09/Users-Contact-Information-150x150.png" class="attachment-thumbnail" alt="Users Contact Information" title="Users Contact Information" /></a> <a
href='http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/users-adding-team-members/' title='Users Adding team members'><img
width="150" height="150" src="http://www.intechgrity.com/wp-content/uploads/2010/09/Users-Adding-team-members-150x150.png" class="attachment-thumbnail" alt="Users Adding team members" title="Users Adding team members" /></a> <a
href='http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/users-editing-team-members/' title='Users Editing team members'><img
width="150" height="150" src="http://www.intechgrity.com/wp-content/uploads/2010/09/Users-Editing-team-members-150x150.png" class="attachment-thumbnail" alt="Users Editing team members" title="Users Editing team members" /></a> <a
href='http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/users-apply-for-events/' title='Users Apply for events'><img
width="150" height="150" src="http://www.intechgrity.com/wp-content/uploads/2010/09/Users-Apply-for-events-150x150.png" class="attachment-thumbnail" alt="Users Apply for events" title="Users Apply for events" /></a> <a
href='http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/users-checking-application-details/' title='Users Checking application details'><img
width="150" height="150" src="http://www.intechgrity.com/wp-content/uploads/2010/09/Users-Checking-application-details-150x150.png" class="attachment-thumbnail" alt="Users Checking application details" title="Users Checking application details" /></a> <a
href='http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/user-particular-app-check-via-thickbox/' title='User Particular app check via thickbox'><img
width="150" height="150" src="http://www.intechgrity.com/wp-content/uploads/2010/09/User-Particular-app-check-via-thickbox-150x150.png" class="attachment-thumbnail" alt="User Particular app check via thickbox" title="User Particular app check via thickbox" /></a><p>I am really in rush today. As I have loads of works left. Hope you find this plugin useful and can use this to manage your own college&#8217;s fest. Note that <em>the plugin is currently a Release Candidate, means I will see and bug fix as I use this on my own college&#8217;s website</em>. Once done, I will notify for the public release. Enjoy&#8230;</p><p>And one more thing, as I have worked for this, I have learned some cool things as well, which I can&#8217;t wait to share with you! So stay tuned.</p><p>Related posts:<ol><li><a
href='http://www.intechgrity.com/move-intense-debate-comment-from-blogger-to-wordpress-using-export-xml/' rel='bookmark' title='Move Intense Debate Comment from Blogger to WordPress using Export XML ~ First WP plugin by iTg'>Move Intense Debate Comment from Blogger to WordPress using Export XML ~ First WP plugin by iTg</a></li><li><a
href='http://www.intechgrity.com/determine-plugin-directory-and-url-in-wordpress-using-wp-api/' rel='bookmark' title='Determine Plugin Directory and URL in WordPress using WP API'>Determine Plugin Directory and URL in WordPress using WP API</a></li><li><a
href='http://www.intechgrity.com/wp-category-post-list-plugin-list-your-posts-filtered-by-categories-with-thumbnails/' rel='bookmark' title='WP Category Post List Plugin &#8211; List your posts filtered by categories with thumbnails'>WP Category Post List Plugin &#8211; List your posts filtered by categories with thumbnails</a></li><li><a
href='http://www.intechgrity.com/how-to-add-your-own-stylesheet-to-your-wordpress-plugin-settings-page-or-all-admin-page/' rel='bookmark' title='How to add your own stylesheet to your WordPress plugin settings page or All Admin page'>How to add your own stylesheet to your WordPress plugin settings page or All Admin page</a></li><li><a
href='http://www.intechgrity.com/jquery-fade-n-slide-button-animator-plugin-by-itg/' rel='bookmark' title='jQuery Fade n Slide Button Animator Plugin by iTg'>jQuery Fade n Slide Button Animator Plugin by iTg</a></li></ol></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p>]]></content:encoded> <wfw:commentRss>http://www.intechgrity.com/wp-simple-event-management-plugin-by-itg-manage-college-fests-and-events/feed/</wfw:commentRss> <slash:comments>14</slash:comments> </item> <item><title>How to add your own stylesheet to your WordPress plugin settings page or All Admin page</title><link>http://www.intechgrity.com/how-to-add-your-own-stylesheet-to-your-wordpress-plugin-settings-page-or-all-admin-page/</link> <comments>http://www.intechgrity.com/how-to-add-your-own-stylesheet-to-your-wordpress-plugin-settings-page-or-all-admin-page/#comments</comments> <pubDate>Mon, 30 Aug 2010 18:55:48 +0000</pubDate> <dc:creator>Swashata</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[Wordpress APIs]]></category> <category><![CDATA[wordpress]]></category> <category><![CDATA[wordpress api]]></category> <category><![CDATA[wordpress functions]]></category><guid isPermaLink="false">http://www.intechgrity.com/?p=691</guid> <description><![CDATA[<p><p>Original post published <a
href="<a href="http://www.intechgrity.com/how-to-add-your-own-stylesheet-to-your-wordpress-plugin-settings-page-or-all-admin-page/">How to add your own stylesheet to your WordPress plugin settings page or All Admin page</a>">here</a></p><p>So, you have got a cool new plugin with a dashing settings page. You have your very own HTML structure and CSS as well to style them&#8230; But, you are confused how to tell WordPress to include the StyleSheet in the admin page head? Well, this happened with me also. The primary solution I thought [...]</p></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p> Related posts:<ol><li><a
href='http://www.intechgrity.com/determine-plugin-directory-and-url-in-wordpress-using-wp-api/' rel='bookmark' title='Determine Plugin Directory and URL in WordPress using WP API'>Determine Plugin Directory and URL in WordPress using WP API</a></li><li><a
href='http://www.intechgrity.com/add-dynamic-login-logout-n-site-admin-button-to-wordpress-using-wp-api/' rel='bookmark' title='Add dynamic Login Logout n Site Admin button to WordPress using WP API'>Add dynamic Login Logout n Site Admin button to WordPress using WP API</a></li><li><a
href='http://www.intechgrity.com/properly-add-pagination-to-your-wordpress-plugin/' rel='bookmark' title='Properly add pagination to your WordPress Plugin'>Properly add pagination to your WordPress Plugin</a></li><li><a
href='http://www.intechgrity.com/parse-id-list-from-csv-using-new-wordpress-3-0-api-the-right-way-of-doing/' rel='bookmark' title='Parse ID list from CSV, using new WordPress 3.0 API &#8211; The right way of doing'>Parse ID list from CSV, using new WordPress 3.0 API &#8211; The right way of doing</a></li><li><a
href='http://www.intechgrity.com/setting-post-thumbnail-on-wordpress-with-custom-size-and-cropping-a-simpler-approach/' rel='bookmark' title='Setting Post Thumbnail on WordPress with custom size and Cropping &#8211; A simpler approach'>Setting Post Thumbnail on WordPress with custom size and Cropping &#8211; A simpler approach</a></li></ol>]]></description> <content:encoded><![CDATA[<p>Original post published <a
href="<a href="http://www.intechgrity.com/how-to-add-your-own-stylesheet-to-your-wordpress-plugin-settings-page-or-all-admin-page/">How to add your own stylesheet to your WordPress plugin settings page or All Admin page</a>">here</a></p><p><a
href="http://www.intechgrity.com/wp-content/uploads/2010/08/enqueue-stylesheet-wordpress.png"><img
class="aligncenter size-full wp-image-700" title="enqueue-stylesheet-wordpress" src="http://www.intechgrity.com/wp-content/uploads/2010/08/enqueue-stylesheet-wordpress.png" alt="" width="500" height="300" /></a>So, you have got a cool new plugin with a dashing settings page. You have your very own HTML structure and CSS as well to style them&#8230; But, you are confused how to tell WordPress to include the StyleSheet in the admin page head?</p><p>Well, this happened with me also. The primary solution I thought of was either include the CSS inside <span
class="code">&lt;style&gt;</span> tag or use <span
class="spanlight">admin_head</span> hook to output (<em>echo to be precise</em>) the <span
class="code">&lt;link&gt;</span> to the CSS file. It worked for sure, but the problem was</p><ol><li>For style tag, I need to know the directory where the plugin is, to properly output my images. Its easy for default WP directory structure, but will not work for WP installations with custom directory.</li><li>For admin_head hook, the stylesheet will get loaded on all the pages and <em>may conflict with other plugin&#8217;s CSS</em>. I really did not want this to happen.</li></ol><p>So, I digged a little bit and after looking into the WordPress codex found the perfect solution for this. Here is how to do this in the perfect way:</p><h2>#0: How to add CSS to all the Admin Pages:</h2><p>Just in case, you want to enqueue your CSS to the whole admin panel, I thought of putting this example as well. You have already developed a WordPress Plugin, so I don&#8217;t have to explain every bits of the code. Here is a sample example, how to print your StyleSheet to the whole admin panel or WordPress&#8230;</p><pre class="brush: php; title: ; notranslate">
/**
 * Lets start with a General CSS Inclusion
 * We will use admin_head hook to enqueue our CSS file
 * This will print the CSS to all the admin pages
 */

/**
 * First the enqueue function
 */
function itg_admin_css_all_page() {
    /**
     * Register the style handle
     */
    wp_register_style($handle = 'itg-admin-css-all', $src = plugins_url('css/admin-all.css', __FILE__), $deps = array(), $ver = '1.0.0', $media = 'all');

    /**
     * Now enqueue it
     */
    wp_enqueue_style('itg-admin-css-all');
}

/**
 * Finally hook the itg_admin_css_all_page to admin_print_styles
 * As it is done during the init of the admin page, so the enqueue gets executed.
 * This can also be attached to the admin_init, or admin_menu hook
 */
add_action('admin_print_styles', 'itg_admin_css_all_page');
</pre><p>Pretty easy right? What we have done is:</p><ul><li>Used a function <span
class="code">itg_admin_css_all_page</span> to register our StyleSheet and enqueue it.</li><li>Added an action to the <span
class="code">admin_print_styles</span> hook, to execute that function.</li></ul><p>And we are all set! This will print your CSS file to the Admin Panel.<a
href="http://www.intechgrity.com/wp-content/uploads/2010/08/general-css.png"><img
class="aligncenter size-medium wp-image-701" title="general css" src="http://www.intechgrity.com/wp-content/uploads/2010/08/general-css-300x142.png" alt="" width="300" height="142" /></a></p><h2>#1: A little about the enqueue and register functions:</h2><p>You can see we have passed several parameters to the function wp_register_style and wp_enqueue_style. Both of them use the same parameters with some difference:</p><ul><li><span
class="spanlight">wp_register_style</span> registers the stylesheet but does not print it. If registered, then it can be called anytime and anywhere from your plugin. This is also useful if some of your StyleSheets depends on other stylesheets. Then the dependencies have to be registered first. Then all of the must be enqueued with their dependencies specified in proper manner. If you are thinking how this dependencies work, then we are getting to that soon!</li><li><span
class="spanlight">wp_enqueue_style</span> either prints a previously registered style or registers if not already. Same parameters can be passed through. But it is recommended to use <em><strong>register_style</strong></em> first and then <em><strong>enqueue_style</strong></em>.</li></ul><h3>Parameter lists:</h3><ul><li><span
class="spanlight">handle</span>: The name of the registered stylesheet. This is used in enqueue_style to print the sheet.</li><li><span
class="spanlight">src</span>: The location of the CSS file. Note that we have used here intelligently the plugins_url API. You can read more about it <a
href="http://www.intechgrity.com/determine-plugin-directory-and-url-in-wordpress-using-wp-api/">here</a>.</li><li><span
class="spanlight">deps</span>: The dependencies. The values are written as a form of array. Say, you have sheet2 which depends on sheet1 and sheet0.  Then pass them as <span
class="code">array(&#8216;sheet0&#8242;, &#8216;sheet1&#8242;)</span>.</li><li><span
class="spanlight">ver</span>: The version of the stylesheet. This will add a query parameter to the CSS file. [<em>http://your.host/wp-include/plugins/your-plugin/css/style.css?ver=1.0.1</em>] This ensures that if you update the version then the user gets the new CSS, instead of caching.</li><li><span
class="spanlight">media</span>: The CSS media attribute.</li></ul><p>Seems great right? Now lets see how we enqueue our CSS to a specific plugin page.</p><h2>#2: How to add CSS to your specific Plugin Settings page:</h2><p>By now, you should be knowing how to add your own plugin page using API&#8217;s like <span
class="code">add_options_page</span> <span
class="code">add_menu_page</span> etc. If not, then <a
href="http://codex.wordpress.org/Adding_Administration_Menus">this is the best place</a> for you to start. Lets see how we add a settings page and link a CSS. Have a look into this code:</p><pre class="brush: php; html-script: true; title: ; notranslate">
&lt;?php
/**
 * Now add our own Settings page
 * Also attach another CSS file there
 */
/**
 * The function to print the page
 */
function itg_admin_css_custom_settings_page() {
    ?&gt;
    &lt;div class=&quot;wrap&quot;&gt;
        &lt;h2&gt;Welcome to the Custom CSS Page demo&lt;/h2&gt;
        &lt;small&gt;Demo Plugin developed by &lt;a href=&quot;http://www.swashata.me&quot;&gt;Swashata&lt;/a&gt; | &lt;a href=&quot;http://www.intechgrity.com&quot;&gt;InTechgrity&lt;/a&gt;&lt;/small&gt;
        &lt;?php
        if($_SERVER['REQUEST_METHOD'] == 'POST') {
            ?&gt;
            &lt;div class=&quot;updated fade&quot;&gt;Hi &lt;span class=&quot;big_red&quot;&gt;&lt;?php echo $_POST['your_name']; ?&gt;&lt;/span&gt;! See we got your name.&lt;/div&gt;
            &lt;?php
        }
        ?&gt;
        &lt;form method=&quot;post&quot; action=&quot;&quot;&gt;
            &lt;ul&gt;
                &lt;li&gt;Howdy! Would you like to enter your name??!&lt;/li&gt;
                &lt;li&gt;&lt;label for=&quot;your_name&quot;&gt;Your name please &amp;raquo;&lt;/label&gt; &lt;input id=&quot;your_name&quot; name=&quot;your_name&quot; value=&quot;...&quot; type=&quot;text&quot; /&gt;&lt;/li&gt;
                &lt;li&gt;&lt;input type=&quot;submit&quot; class=&quot;button-primary&quot; value=&quot;Submit Name&quot; /&gt;&lt;/li&gt;
            &lt;/ul&gt;
        &lt;/form&gt;
    &lt;/div&gt;
    &lt;?php
}

/**
 * The enqueue function
 * Registers and enqueue the CSS
 */
function itg_admin_css_custom_page() {
    /** Register */
    wp_register_style('itg-plugin-page-css', plugins_url('css/admin-cus.css', __FILE__), array(), '1.0.0', 'all');

    /** Enqueue */
    wp_enqueue_style('itg-plugin-page-css');

    /**
     * Enqueue without Register
     * Just for the sake of demonstration
     */
    wp_enqueue_style('itg-plugin-page-css-2', plugins_url('css/admin-cus2.css', __FILE__), array(), '1.0.2', 'all');
}
/**
 * The function to hook the enqueue function
 * And Add the Menu page
 * We can seperate the enqueue but this is the best practice
 * Use a little of your head and find out why? <img src='http://www.intechgrity.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />
 */
function itg_admin_css_menu_init() {
    /** Add options page and get the reference through a variable */
    $itg_admin_menu = add_options_page('iTg Admin panel CSS demo', 'itg CSS Admin', 'manage_options', 'itg_css_admin_page', 'itg_admin_css_custom_settings_page');

    /**
     * Now use the reference to conditionally attach the script
     * We will add an action to admin_print_style with conditional tag
     * Also we will execute the itg_admin_css_custom_page function which enqueues the CSS
     */
    add_action('admin_print_styles-' . $itg_admin_menu, 'itg_admin_css_custom_page');
}

/**
 * All done.
 * Now hook the itg_admin_css_menu_init to the admin_menu
 */
add_action('admin_menu', 'itg_admin_css_menu_init');
?&gt;
</pre><p>Lets see the sequence of the execution of the functions:</p><ul><li>We add the <span
class="code">admin_menu</span> hook with a callback function named <span
class="code">itg_admin_css_menu_init</span></li><li>The <span
class="code">itg_admin_css_menu_init</span> function does two thing<br
/> Adds up an option page named <em><strong>itg CSS Admin</strong></em> with a callback function <span
class="code">itg_admin_css_custom_settings_page</span><br
/> Adds another hook to <span
class="code">admin_print_styles</span> in a conditional manner which calls the function <span
class="code">itg_admin_css_custom_page</span>.</li><li><span
class="code">itg_admin_css_custom_settings_page</span> Generates the plugin settings page.</li><li><span
class="code">itg_admin_css_custom_page</span> Enqueues the styles.</li></ul><p>Now that was easy, eh?<a
href="http://www.intechgrity.com/wp-content/uploads/2010/08/custom-css.png"><img
class="aligncenter size-medium wp-image-699" title="custom css" src="http://www.intechgrity.com/wp-content/uploads/2010/08/custom-css-300x142.png" alt="" width="300" height="142" /></a></p><p>Note that the main thing was <span
class="code">&#8216;admin_print_styles-&#8217; . $itg_admin_menu</span> which adds the condition to print the style only on the specific page.</p><p>For your ease, we have put together a demo plugin which you can download and test. Also check the source code to understand more&#8230;</p><div
class="demo-download lonely"><a
class="download" title="Wordpress Enqueue Style Demonstration plugin Downloaded 169" href="http://www.intechgrity.com/downloads/9">Download Now</a></div><h4 class="faq">External Resources:</h4><ul><li><a
href="http://codex.wordpress.org/Function_Reference/wp_register_style">WordPress Codex: wp_register_style</a>.</li><li><a
href="http://codex.wordpress.org/Function_Reference/wp_enqueue_style">WordPress Codex: wp_enqueue style</a>.</li><li><a
href="http://iamzed.com/2010/01/07/using-wordpress-wp_enqueue_style-with-conditionals/">Using enqueue with conditional IE tag</a>: An advanced technique to include conditional IE tags for CSS hacks.</li></ul><p>And that was all. <strong>If it was useful for you then do give your feedback</strong>. Also if you have any problem then just drop in!</p><p>Related posts:<ol><li><a
href='http://www.intechgrity.com/determine-plugin-directory-and-url-in-wordpress-using-wp-api/' rel='bookmark' title='Determine Plugin Directory and URL in WordPress using WP API'>Determine Plugin Directory and URL in WordPress using WP API</a></li><li><a
href='http://www.intechgrity.com/add-dynamic-login-logout-n-site-admin-button-to-wordpress-using-wp-api/' rel='bookmark' title='Add dynamic Login Logout n Site Admin button to WordPress using WP API'>Add dynamic Login Logout n Site Admin button to WordPress using WP API</a></li><li><a
href='http://www.intechgrity.com/properly-add-pagination-to-your-wordpress-plugin/' rel='bookmark' title='Properly add pagination to your WordPress Plugin'>Properly add pagination to your WordPress Plugin</a></li><li><a
href='http://www.intechgrity.com/parse-id-list-from-csv-using-new-wordpress-3-0-api-the-right-way-of-doing/' rel='bookmark' title='Parse ID list from CSV, using new WordPress 3.0 API &#8211; The right way of doing'>Parse ID list from CSV, using new WordPress 3.0 API &#8211; The right way of doing</a></li><li><a
href='http://www.intechgrity.com/setting-post-thumbnail-on-wordpress-with-custom-size-and-cropping-a-simpler-approach/' rel='bookmark' title='Setting Post Thumbnail on WordPress with custom size and Cropping &#8211; A simpler approach'>Setting Post Thumbnail on WordPress with custom size and Cropping &#8211; A simpler approach</a></li></ol></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p>]]></content:encoded> <wfw:commentRss>http://www.intechgrity.com/how-to-add-your-own-stylesheet-to-your-wordpress-plugin-settings-page-or-all-admin-page/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Getting Post thumbnail on WordPress 3 w/ w/o specific Post ID</title><link>http://www.intechgrity.com/getting-post-thumbnail-on-wordpress-3-w-wo-specific-post-id/</link> <comments>http://www.intechgrity.com/getting-post-thumbnail-on-wordpress-3-w-wo-specific-post-id/#comments</comments> <pubDate>Mon, 30 Aug 2010 04:16:51 +0000</pubDate> <dc:creator>Swashata</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[Wordpress APIs]]></category> <category><![CDATA[wordpress api]]></category> <category><![CDATA[wordpress functions]]></category><guid isPermaLink="false">http://www.intechgrity.com/?p=682</guid> <description><![CDATA[<p><p>Original post published <a
href="<a href="http://www.intechgrity.com/getting-post-thumbnail-on-wordpress-3-w-wo-specific-post-id/">Getting Post thumbnail on WordPress 3 w/ w/o specific Post ID</a>">here</a></p><p>Previously we have discussed about how to activate and set custom post featured image sizes using two WordPress APIs, add_theme_support and add_image_size. After this, the tutorial on how to actually use the generated thumbnails, was really pending. And I am really sorry that I could not bring this tutorial the day after I published the [...]</p></p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p> No related posts.]]></description> <content:encoded><![CDATA[<p>Original post published <a
href="<a href="http://www.intechgrity.com/getting-post-thumbnail-on-wordpress-3-w-wo-specific-post-id/">Getting Post thumbnail on WordPress 3 w/ w/o specific Post ID</a>">here</a></p><p><a
href="http://www.intechgrity.com/wp-content/uploads/2010/08/setting-wp-post-thumbnai.png"><img
class="aligncenter size-full wp-image-671" title="setting-wp-post-thumbnai;" src="http://www.intechgrity.com/wp-content/uploads/2010/08/setting-wp-post-thumbnai.png" alt="" width="500" height="300" /></a>Previously we have discussed about how to <a
href="http://www.intechgrity.com/setting-post-thumbnail-on-wordpress-with-custom-size-and-cropping-a-simpler-approach/">activate and set custom post featured image sizes </a>using two WordPress APIs, <span
class="code">add_theme_support</span> and <span
class="code">add_image_size</span>. After this, the tutorial on how to actually use the generated thumbnails, was really pending. And I am really sorry that I could not bring this tutorial the day after I published the previous tutorial. I really became busy with the WordPress Plugin and my collage&#8217;s website development.</p><p>But, anyways, its never too late.. So today we will discuss how we can use WordPress&#8217; another two API&#8217;s <span
class="code">the_post_thumbnail</span> and <span
class="code">get_the_post_thumbnail</span>.</p><h2>#1: Using the_post_thumbnail:</h2><p>The primary API to get and display the post thumbnail. So, this will echo the IMG HTML with the SRC to the post thumbnails&#8230; Here are its specifications:</p><h3>#1.1: Parameters:</h3><p>It accepts two parameters, size and attribute.</p><ul><li><span
class="code">$size</span>: (<em>mixed</em>) The size of the featured thumbnail to display. It can be a string or an array with height, width.</li><li><span
class="code">$attr</span>: (<em>array</em>) The sets of attributes. It accepts the following parameters. Given are their default values:<pre class="brush: php; title: ; notranslate">
$default_attr = array(
    'src'	=&gt; $src,
    'class'	=&gt; &quot;attachment-$size&quot;,
    'alt'	=&gt; trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
    'title'	=&gt; trim(strip_tags( $attachment-&gt;post_title )),
);
</pre></li></ul><h3>#1.2: Usage Notes:</h3><p>The usage is restricted in a way that, it <strong>should be used within the Loop</strong>. So, you can not pass post id to get and display specific thumbnails or featured images. If that is the case, then use get_the_post_thumbnail.</p><h3>#1.3: Basic usage and Example:</h3><p>Below is the basic syntax guide.</p><pre class="brush: php; title: ; notranslate">
/**
 * Getting post thumbnail with predefined size (custom-thumbnail)
 * and Custom sets of attr
 */
$my_thumb_attr = array(
    'class' =&gt; 'my-class',
    'title' =&gt; 'Go to the post'
);
the_post_thumbnail('custom-thumbnail', $my_thumb_attr);

/**
 * Basic usage with custom size
 */
the_post_thumbnail(array(100, 100));
</pre><p>This is the complete example&#8230;</p><h4>#1.3.1: Our theme&#8217;s functions.php file:</h4><p>Here we add the thumb support and make a custom size of 256X256.</p><pre class="brush: php; title: ; notranslate">
/**
 * Enable the post thumbnail support
 * Add the custom 150X150 image size
 */
if(function_exists('add_theme_support')) {
    /** Register the post thumbnail */
    add_theme_support('post-thumbnails');

    /** Register custom size */
    add_image_size('itg-ex', 100, 100, true);
}
</pre><h4>#1.3.2: The index.php file:</h4><p>Here we show the post excerpt with our custom thumbnail.</p><pre class="brush: php; html-script: true; title: ; notranslate">
&lt;?php
/**
 * Loop through the posts
 * Use the excerpt and our custom thumbnail size
 */
if(have_posts()) : while(have_posts()) : the_post();
?&gt;
&lt;div class=&quot;post-content&quot;&gt;
    &lt;h2&gt;&lt;a href=&quot;&lt;?php the_permalink(); ?&gt;&quot;&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;
    &lt;div class=&quot;content&quot;&gt;
        &lt;?php
        /**
         * Check to see if post has thumbnail
         */
        if(has_post_thumbnail()) {
            ?&gt;
            &lt;div class=&quot;my_thumb&quot;&gt;
                &lt;?php the_post_thumbnail('itg-ex', array('class' =&gt; 'alignright')); ?&gt;
            &lt;/div&gt;
            &lt;?php the_excerpt(); ?&gt;
            &lt;?php
        }
        ?&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;?php
endwhile; endif;
?&gt;
</pre><h2>#2: Using get_the_post_thumbnail:</h2><p>This is a bit advanced than <span
class="code">the_post_thumbnail</span>. It allows you to pass through the post id to get the thumbnail. Note that this will return the IMG HTML instead of echo-ing it.</p><h3>#2.1: Available parameters:</h3><p>In addition to the previous two parameters, it gives another parameter <span
class="code">$id</span>, to pass the post ID.</p><ul><li><span
class="code">$id</span>: (<em>integer</em>) This is a <strong>Required</strong> parameter. It gets the thumbnail from the given post id.</li><li><span
class="code">$size</span> and <span
class="code">$attr</span>: Same as the_post_thumbnail.</li></ul><h3>#2.2: Usage Note:</h3><p>This API does not automatically get the post thumbnail, when used inside the loop. You are required to pass in the <em>id</em> parameter no matter where you use it.</p><h3>#2.3: Usage example:</h3><p>This depends upon your necessity. For displaying inside the main Loop, you can use <span
class="code">the_post_thumbnail</span>, but in case you are using <span
class="code">get_posts</span> then you can use <span
class="code">get_the_post_thumbnail</span> to get and store the featured image html. For example, I am using the following peace of code for my new <a
href="http://wordpress.org/extend/plugins/wp-category-posts-list/">widget plugin</a>. (<em>It&#8217;s RC now! You can safely install. The next post will be about the plugin&#8217;s final release <img
src='http://www.intechgrity.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </em> )</p><pre class="brush: php; title: ; notranslate">
&lt;?php
/**
 * Get the posts by a category
 */
$my_posts = get_posts(array('cat' =&gt; 2));
/**
 * Initiate the output
 */
$output = '';
/** Loop through the post */
foreach($my_posts as $post) {

    /** Add Thumbnail to the anchor if present
     * Else The post title
     */
    $output .= '&lt;li&gt;&lt;a href=&quot;' . get_permalink($post-&gt;ID) . '&quot;&gt;';
    if(has_post_thumbnail($post-&gt;ID))
        $output .= get_the_post_thumbnail($post-&gt;ID);
    else
        $output .= $post-&gt;post_title;

    /**
     * Close the widget
     */
    $output .= '&lt;/a&gt;&lt;/li&gt;';
}
echo $output;
?&gt;
</pre><p>Also, here are some basic implementation:</p><pre class="brush: php; title: ; notranslate">
get_the_post_thumbnail($id);                  // without parameter -&gt; Thumbnail

get_the_post_thumbnail($id, 'thumbnail');     // Thumbnail
get_the_post_thumbnail($id, 'medium');        // Medium resolution
get_the_post_thumbnail($id, 'large');         // Large resolution

get_the_post_thumbnail($id, array(100,100) ); // Other resolutions
</pre><h2>#3: Notes and Tips:</h2><ul><li>While using any of the API, your theme or plugin need to have the post-thumbnails enabled. You should read this post to get detailed information about how to enable them and how to add different image sizes.</li><li>You can use has_post_thumbnail to check if the post has featured image set or not.</li><li>Calling any of the API without <span
class="code">add_theme_support( &#8216;post-thumbnails&#8217;)</span> will give Fatal Error of calling undefined function.</li><li>For previous posts, whose featured image were set before registering a custom size, will give HTML sized (maintaining aspect ratio) images, no matter you have enabled cropping via the <span
class="code">add_image_size</span> or not. Viper007&#8242;s regenerate thumbnail can be used in such case. Although I have not tested it, but I have a feeling that it will work <img
src='http://www.intechgrity.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</li></ul><h4 class="faq">External Resources:</h4><ul><li><a
href="http://codex.wordpress.org/Function_Reference/the_post_thumbnail">WordPress codex the_post_thumbnail API</a>.</li><li><a
href="http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail">WordPress codex get_the_post_thumbnail API</a>.</li><li><a
href="http://codex.wordpress.org/Function_Reference/has_post_thumbnail">WordPress codex has_post_thumbnail API documentation</a>.</li><li><a
href="http://wpengineer.com/1930/the-ultimative-guide-for-the_post_thumbnail-in-wordpress-2-9/">The ultimate post thumbnail guide for WP 2.9+</a>.</li></ul><p>And that is all! Hope, you have enjoyed the article. <strong>Do give us your feedback and if you face any trouble, feel free to ask</strong>.</p><p>No related posts.</p><p>- By <a
href="http://www.intechgrity.com">InTechgrity - Amalgamating Life &amp; Technology</a></p>]]></content:encoded> <wfw:commentRss>http://www.intechgrity.com/getting-post-thumbnail-on-wordpress-3-w-wo-specific-post-id/feed/</wfw:commentRss> <slash:comments>10</slash:comments> </item> </channel> </rss><!-- W3 Total Cache: Minify debug info:
Engine:             disk: basic
Theme:              c15c7
Template:           category
--><!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: enhanced
Database Caching 8/131 queries in 0.087 seconds using disk: basic
Object Caching 5986/6168 objects using disk: basic

Served from: www.intechgrity.com @ 2012-05-26 17:27:08 -->

