Jul 17, 2011

Fully Customized Wordpress Twenty Ten Theme

Fully customized twenty ten theme, download and have fun, its fully free.

Credit:http://www.dynamicwp.net/free-themes/twentyeleven-theme/


download

Jul 15, 2011

Wordpress Twenty Eleven Theme sidebar on Pages and Posts

Recently I added a post on how to add a sidebar on single(posts-page) or single.php

So today I am with one more child theme which will add sidebar on page.php i.e. pages also

So just download and install this child theme. This new child theme will enable the sidebar on page.php and also on single.php page.


download

Jul 14, 2011

Wordpress Make A Featured Post Jquery Ticker | Wordpress Make featured Posts

Now a days blogging is very common, every human being wants to have their own blog or website where they can put some useful stuffs, but out of that blogs, there are some important or hot blogs, which we say as featured blogs, if you are wordpress user then why to adopt plugin, where you can create a simple one.
So lets get started.

First decide where you want to display the featured post section, usually it is on the home page. So considering it on home page, we will edit two files in this tutorial.
index.php
header.php

So lets get started with header.php, open that file, and in the head section put this small piece of code

[css]
<style>
#posts-container{ }
#posts-container ul li div{
border: 1px solid #aaaaaa;
background: #ffffff;}
</style>
[/css]

You can see that the style is not fully complete, cause I have left it upto you, so that you can have your own style, but if you leave this also it doesn't matter, cause this will also give the blog a simple and neat looks to featured posts

After styling we will add some javascript code to head section.
Be very careful while adding javascript code, as it may conflict with other js files.

[javascript]
<script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/jquery.vticker-min.js"></script>
<script type="text/javascript">
jQuery(function(){
jQuery('#posts-container').vTicker({
speed: 600,
pause: 3000,
animation: 'fade',
mousePause: true,
showItems: 3
});
});
</script>
[/javascript]

As you can see the $ is been replaced by jQuery just to avoid the conflict.
So the final header code will look something like this:

[html]
<style type="text/css" media="all">
#posts-container{ }
#posts-container ul li div{
border: 1px solid #aaaaaa;
background: #ffffff;}
</style>
<script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/jquery.vticker-min.js"></script>
<script type="text/javascript">
jQuery(function(){
jQuery('#posts-container').vTicker({
speed: 600,
pause: 3000,
animation: 'fade',
mousePause: true,
showItems: 3
});
});
</script>
[/html]

In the above javascript, you can change the attribut as per your need, like speed, animation, on-mouse-over-pause etc etc. You can change it anytime. I have kept the js file into the js folder of the theme, if you are keeping it in any other folder then be sure to edit the code.

This part completes the main jquery.
But the question is how will you select the posts as featured?
For this we can use custom fields.
Add a new custom field in your Add-new or Edit posts page, and replicate the same as in below image
How TO Add Custom Field

Tip: Instead Of Manually Adding one-one custom field, I recommend that you use More Fields Plugin. Which Will help you to have a custom field for all post.

Do the above step for only those posts which you want to display as featured posts.

Now open index.php file and just paste this code just above the if ( have_posts() ) code

[php]
<?php
$key = 'featured';
$themeta = get_post_meta($post->ID, $key, TRUE);
if($themeta == 'no') {
echo 'No Featured Posts';
}
elseif($themeta == 'yes'){
?>
<?php query_posts('meta_key=featured&meta_value=Yes');  ?>
<div style="border:4px solid #666666; -moz-border-radius:5px; -webkit-border-radius:5px; padding:12px; color:#333333;font-weight:bold; background-color:#FFFFE0;">
<h1 style="color:#880000; font-weight:bold; font-size:18px; text-decoration:underline;">Featured Posts:</h1>
<div id="posts-container">
<ul>
<?php while ( have_posts() ) : the_post(); ?>
<li>
<a href="<?php the_permalink() ?>" style="color:#333333;"><?php echo the_title() ?></a>
</li>
<?php endwhile; ?>
</ul>
</div>
</div>

<?php wp_reset_query();

}?>
[/php]

In this code we are taking the posts which has custom field value set to yes for featured, and displaying it in a list format, here I have given the css into the style tag of a div, you can change it any time as per your theme design.  I am also using wp_reset_query just to be sure that it doesn't conflicts with other posts.

This above tutorial is just going to display posts title, but if you also want to display posts content, then just make a small change to the above code, just add the 3 line to the code.

[php]
<li>
<a href="<?php the_permalink() ?>" style="color:#333333;"><?php echo the_title() ?></a>
<br><em><php echo the_excerpt(); ?></em>
</li>
[/php]

You can see the demo on my websites homepage
Demo | Download [download id="3"]

Create a WordPress theme | How to create WordPress Theme

First thing to do is to create a sub-folder in the wp-content/themes directory in your WordPress folder. Lets say we name it as "My_Theme". Also note that the name of the folder should correspond to the name of the theme you want to create. To do this you can either use your favorite FTP client or the File Manager tool in your cPanel.

You should first think of the layout of your website, i.e how your website will look..??..In this tutorial we will create a wordpress theme which will contain a header , sidebar , main content area and lastly a footer at the end as shown in the fig.



We will have to create the following files in the directory we made i.e "My_Theme" as I mentioned earlier. Following are the files :-

  • header.php - This file will contain the code for the header section of the theme;

  • index.php - This is the main file for the theme. It will contain the code for the Main Area and will specify where the other files will be included;

  • sidebar.php - This file will contain the information about the sidebar;

  • footer.php - This file will handle your footer;

  • style.css - This file will handle the styling of your new theme;


You can either create those files locally with a simple text editor(like notepad for example) and upload them via FTP or you can use the File Manager tool in your cPanel to create the files directly on your hosting account.

We will now go through contents of each files.

The header.php file


following code should be added to this file

[php]

<html>
<head>
<title>Tutorial theme</title>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
</head>
<body>
  <div id="wrapper">
    <div id="header">
      <h1>HEADER</h1>
    </div>

[/php]

It basically contains simple HTML code with a line containing a php code and a standard WordPress function. In this file you are dealing with your meta tags such as the title of your website, meta description and the keywords for your page.

After the title the line we add <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>"> this will tell WordPress to load the style.css file. To handle all the styling/looks of your website. The <?php bloginfo('stylesheet_url'); ?> part of the line is a WordPress function that actually loads the stylesheet(stylesheet.css) file.

Next, we have added the beginning of a "div" with class wrapper which will be the main container of the website. We have set class for it so we can modify it via the style.css file.

The next step we have added a simple label HEADER wrapped in a "div" with class "header" which will be later specified in the stylesheet file.

The index.php file


following code should be added to this file



[php]</p>
<p style="text-align: left;"><?php get_header(); ?>

<div id="main">
  <div id="content">
    <h1>Main Area</h1>
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <h1><?php the_title(); ?></h1>
    <h4>Posted on <?php the_time('F jS, Y') ?></h4>
    <p><?php the_content(__('(more...)')); ?></p>
    <hr>
    <?php endwhile; else: ?>
    <p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
    <?php endif; ?>
  </div>

  <?php get_sidebar(); ?>

  </div>

<div id="delimiter"></div>

<?php get_footer(); ?></p>
<p style="text-align: left;">[/php]

The code in this file begins with <?php get_header(); ?> which will include the header.php file and the code in it in the main page. It uses an internal WordPress function to do this. We will explain this in details later in this tutorial. Then we have placed a Main Content Area text to indicate which section of your theme is displayed in this area.


The next few lines consist of a PHP code and standard WordPress functions. This code checks whether you have posts in your blog created through the WordPress administrative area and displays them.

Next, we include the sidebar.php file with this line - <?php get_sidebar(); ?>. In this file you can display your post categories, archives etc.

After this line, we insert an empty "div" that will separate the Main Area and the Sidebar from the footer.

Finally, we add one last line - <?php get_footer(); ?> which will include the footer.php file in your page.

 The sidebar.php file


following code should be added to this file

[php]

<div id="sidebar">
  <h2><?php _e('Categories'); ?></h2>
  <ul>
    <?php wp_list_cats('sort_column=name&optioncount=1&hierarchical=0'); ?>
  </ul>

  <h2><?php _e('Archives'); ?></h2>
    <ul>
      <?php wp_get_archives('type=monthly'); ?>
    </ul>
</div>

[/php]

In this file we use internal WordPress functions to display the Categories and Archives of posts. The WordPress function returns them as list items, therefore we have wrapped the actual functions in unsorted lists (the <ul> tags).

The footer.php file


following code should be added to this file

[html]

<div id="footer">
  <h1>FOOTER</h1>
</div>

</div>

</body>
</html>

[/html]

With this code we add a simple FOOTER lable. Instead of this code you can add links, additional text, the copyright information for your theme and additional objects.

The style.css file


following code should be added to this file

[css]

body {
    text-align: center;
}

#wrapper {
    display: block;
    border: 1px #a2a2a2 solid;
    width:90%;
    margin:0px auto;
}

#header {
    border: 2px #a2a2a2 solid;
}

#content {
    width: 75%;
    border: 2px #a2a2a2 solid;
    float: left;
}

#sidebar {
    width: 23%;
    border: 2px #a2a2a2 solid;
    float: right;
}

#delimiter {
    clear: both;
}

#footer {
    border: 2px #a2a2a2 solid;
}

.title {
    font-size: 12pt;
    font-family: Latha;
    font-weight: bold;
}

[/css]

This simple css file sets the basic looks of your theme. Those lines  set the background of your page and surround the main parts of your site with borders for convenience.


And that is it your theme is ready for use.


From now on you can modify the CSS file, add images, animations and other content to your theme in order to achieve the looks you want for your website or blog. Hope this tutorial helped you achieve what you wanted.

Jul 12, 2011

Wordpress Remove Parent Category From Permalink

The easiest way to remove parent category from permalink only if it has a child category is to include the below code in your theme's functions.php file

[php]

// Remove category base
add_filter('category_link', 'no_category_parents',1000,2);
function no_category_parents($catlink, $category_id) {
$category = &get_category( $category_id );
if ( is_wp_error( $category ) )
return $category;
$category_nicename = $category->slug;

$catlink = trailingslashit(get_option( 'home' )) . user_trailingslashit( $category_nicename, 'category' );
return $catlink;
}

// Add our custom category rewrite rules
add_filter('category_rewrite_rules', 'no_category_parents_rewrite_rules');
function no_category_parents_rewrite_rules($category_rewrite) {
//print_r($category_rewrite); // For Debugging

$category_rewrite=array();
$categories=get_categories(array('hide_empty'=>false));
foreach($categories as $category) {
$category_nicename = $category->slug;
$category_rewrite['('.$category_nicename.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
$category_rewrite['('.$category_nicename.')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
$category_rewrite['('.$category_nicename.')/?$'] = 'index.php?category_name=$matches[1]';
}
// Redirect support from Old Category Base
global $wp_rewrite;
$old_base = $wp_rewrite->get_category_permastruct();
$old_base = str_replace( '%category%', '(.+)', $old_base );
$old_base = trim($old_base, '/');
$category_rewrite[$old_base.'$'] = 'index.php?category_redirect=$matches[1]';

//print_r($category_rewrite); // For Debugging
return $category_rewrite;
}

// Add 'category_redirect' query variable
add_filter('query_vars', 'no_category_parents_query_vars');
function no_category_parents_query_vars($public_query_vars) {
$public_query_vars[] = 'category_redirect';
return $public_query_vars;
}
// Redirect if 'category_redirect' is set
add_filter('request', 'no_category_parents_request');
function no_category_parents_request($query_vars) {
//print_r($query_vars); // For Debugging
if(isset($query_vars['category_redirect'])) {
$catlink = trailingslashit(get_option( 'home' )) . user_trailingslashit( $query_vars['category_redirect'], 'category' );
status_header(301);
header("Location: $catlink");
exit();
}
return $query_vars;
}

[/php]

Wordpress Remove Pagination

Ok to remove pagination only from archives page, just past the below snippet to functions.php file

[php]

function no_nopaging($query) {
if ( !is_home() && !is_feed() && '' === $query->get('nopaging') )
$query->set('nopaging', 1);
}

add_action('parse_query', 'yay_nopaging');

[/php]

If you want to remove from other pages, then just change the if condition.

Create A Template In Joomla 1.5 | How to make template in Joomla

So you decided to make your first Joomla template, good idea, Follow the steps below:-

  • Go to your joomla directory>templates, here create a folder named as first_template(You can keep any name, as per your choice)



  • In this new folder, create a file named as "index.php" and one more named as "templateDetails.xml". Then create a folder and named it as "css" and inside this folder make a new file named as "template.css".
    You can create these files using a normal text editor like notepad.



  • The files and folder which we created are the basic and mandatory files which joomla needs.


Explanation of Files
index.php - This file specifies the module positions and the path to your CSS stylesheet file. This is the main and important section of your template.

templateDetails.xml - This file provides the information of your new template to joomla.

css/template.css - As the name suggests, it is used to store your style sheets.

After the above steps go to your administrator>template manager, you will find your new created template displayed there. Just make it as default. and follow the next steps.

The files which we created, now we are going to fill them with codes.

The index.php should contain:

[php]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>" >
<head>
<jdoc:include type="head" />
</head>
[/php]

The lines which we wrote now, is used to specify the beginning of HTML output.
Next we will add the head php code of joomla, which adds all the head section like title, meta etc etc to your output.

[php]
<jdoc:include type="head"/>
[/php]

Now we will add the body.

[php]
<body>
<jdoc:include type="component" />
</body>
</html>
[/php]

The

[php]<jdoc:include type="component" >[/php]

is used to display the main component or content of each page

After the above steps, lets have a look to our new template, so save the file and check your website in browser, to how it looks.

Joomla first look

The above output is just displaying articles with no modules and css, so lets add them.
Open your index.php file and add the following code to body section

[php]
<div id="container">
<div id="header"> <jdoc:include type="modules" name="top" /> </div>
<div id="sidebar_left"> <jdoc:include type="modules" name="left" /> </div>
<div id="content"> <jdoc:include type="component" /></div>
<div id="sidebar_right"class="float"> <jdoc:include type="modules" name="right" /> </div>
<div id="footer"> <jdoc:include type="modules" name="footer" /> </div>
</div>
[/php]

The jdoc:include type="modules" name="left" is used to include module with a left position.

So after the above step, the final index.php should contain the following code:

[php]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>">
<head>
<jdoc:include type="head" />
</head>
<body>
<div id="container">
<div id="header"><jdoc:include type="modules" name="top" /> </div>
<div id="sidebar_left"><jdoc:include type="modules" name="left" /></div>
<div id="content"><jdoc:include type="component" ></div>
<div id="sidebar_right"class="float"><jdoc:include type="modules" name="right" />
</div>
<div id="footer"><jdoc:include type="modules" name="footer" /></div>
</div>
</body>
</html>
[/php]

Now its time to edit templateDetails.xml file, so open it, add the following code:

[php]
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE install PUBLIC "-//Joomla! 1.5//DTD template 1.0//EN" "http://dev.joomla.org/xml/1.5/template-install.dtd">
<install version="1.5" type="template">
<name>first_template</name>
<creationDate>07/2011</creationDate>
<author>Webs Tutorial</author>
<authorEmail>ntechi@webstutorial.com</authorEmail>
<authorUrl>http://www.webstutorial.com</authorUrl>
<copyright>WebsTutorial</copyright>
<license>webstutorial.com TOS</license>
<version>1.0.0<version>
<description>First Joomla Template</description>
<files>
<filename>index.php</filename>
<filename>templateDetails.xml</filename>
<filename>css/template.css</filename>
</files>
<positions>
<position>left</position>
<position>right</position>
<position>top</position>
<position>footer</position>
</positions>
</install>
[/php]

I think its quite understandable from the above xml code, we have used this file to pass some information to joomla, like author of template, date created, template name, description etc etc.
We have used files and filename tag to declare the files we have used.
Position tag is used to give position to modules. This is the actual place to declare a position for module in joomla.

Now finally give some looks to your template, so in css>template.css file, add the following code

[php]
<?xml version="1.0" encoding="utf-8">

* {
padding: 0;
margin: 0;
}
img {
border: 0;
}
body {
font-family: Arial, Helvetica, sans-serif;
line-height: 1.3em;
margin: 0;
padding: 0;
font-size: 13px;
color: #0F0F0F;
}
a:link, a:visited {
text-decoration: underline;
font-weight: normal;
color: #000;
outline: none;
text-align: left;
}
.float {
float: left;
}
.clear {
clear: both;
}
.overall {
background-color: #fff;
}
div.center {
text-align: center;
margin: 0px auto 0 auto;
padding: 0;
width: 950px;
background: #FFFFFF;
}
#container {
width:960px;
margin: auto;
background-color: #f4f9fc;
border: 1px solid #e2e2e2;
text-align: left;
}
#header {
text-align: center;
background-color:#f4f9fc;
height: 80px;
}
#content {
width: 598px;
text-align: left;
background-color:#f4f9fc;
padding: 5px;
}
#sidebar_left {
text-align: center;
background-color:#f4f9fc;
width: 165px;
border-right: 1px solid #e2e2e2;
border-bottom: 1px solid #e2e2e2;
padding: 5px;
}
#sidebar_right {
background-color:#f4f9fc;
text-align: center;
width: 165px;
border-left: 1px solid #e2e2e2;
border-bottom: 1px solid #e2e2e2;
padding: 5px;
}
#footer {
background-color:#f4f9fc;
text-align:center;
border-top: 1px solid #e2e2e2;
border-bottom: 1px solid #e2e2e2;
padding: 5px;
}
[/php]

So after this edit, save everything and check your website now, it will look something like this:
Joomla Final Layout

Your final layout might differ from mine cause of module position.
But you have successfully created your own Joomla template 1.5
Further just edit the css and give an outstanding looks to your template.

How to display errors while the display_errors is off in the php.ini file

Display_error feature is turned off or disabled mainly by your web hosting ISP or provider from the php.ini file. I hope this small tutorial will be of great help to display your php errors.

php.ini file will contain code some what like this

[php]
; display_errors = Off [Security]
; With this directive set to off, errors that occur during the execution of
; scripts will no longer be displayed as a part of the script output, and thus,
; will no longer be exposed to remote users. With some errors, the error message
; content may expose information about your script, web server, or database
; server that may be exploitable for hacking. Production sites should have this
; directive set to off.

; Print out errors (as a part of the output). For production web sites,
; you're strongly encouraged to turn this feature off, and use error logging
; instead (see below). Keeping display_errors enabled on a production web site
; may reveal security information to end users, such as file paths on your Web
; server, your database schema or other information.
display_errors = On
[/php]

Considering some security issues display_errors is usually disabled  by many web hosting companies in order to protect your website from any harm. One way to display errors while the display_errors is off in the php.ini file, is to add these functions at the beginning of your script files .

Just copy and paste this code at the beginning of your script files.

[php]
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);
[/php]

And thats it you can now display errors.

Jul 10, 2011

Wordpress Make HTML5 theme

HTML 5 is the latest and the hottest topic in the web development.
Now a days everybody wants there blogs theme to be in HTML5, even the latest WP-3.2 default theme twenty eleven is also in HTML-5.

So why to wait, convert our current blog old html theme to brand new HTML-5

In this tutorial, you are going to learn the conversion of old HTML to HTML-5

1. Basic Document’s structure

[php]
<!doctype html>
<head>
</head>
<body>
<header>
</header>
<section id="content">
<article>
<header>
</header>
</article>
</section>
<aside>
<nav>
</nav>
</aside>
<footer>
</footer>
</body>
</html>
[/php]

As we can see, that the tags are very new to us. If we add following CSS:
article, aside, figure, footer, header, hgroup, menu, nav, section { display:block; }
we are free to format them like other block elements, e.g.


  • Tag Header, as the name itself indicates that all the head contents like, logo, navigation, search etc will come into it. The usage of this tag inside
    will be presented below.



  • tag used to keep the order in document. We can divide the website into sections, e.g. content, comments, gallery etc.



  • can be used to store our entries – each entry in separate tag! The title and meta of entry should be inside
    – it will have positive impact on our SEO.



  • Our sidebar should be inside






  • If we have footer it is a good practice to put it inside
    . We can have more than one
    , but each should be inside separate
    and one can be directly inside


Tags  like article, header, footer, section can be used more than one time, but the structure has to be maintained.

[php]
<section id="content">
<article>
<header>
</header>
<p>
</p>
<footer>
</footer>
</article>
</section>
[/php]

In header, we can put h3 tag, which is commonly used in wordpress themes content.
If you want to use more then one time hx tags, then it should be wrapped inside hgroup tag.

[php]
<hgroup>
<h3>Main Title</h3>
<h4>Subtitle</h4>
</hgroup>
[/php]

The meta of the post can be wrapped by
, what is a convenient solution.


When it comes to the comments we can treat them like posts and put inside
with >header>,


,
etc. inside.


When we want to refresh our comment form we should definitely use HTML5. Some new input features have been added. Let’s take a look on this:

[php]
<input type="text" name="author" id="comment-form-author" placeholder="Your name" value="" size="22" tabindex="1" required="required">

<input type="email" name="email" id="comment-form-email" placeholder="Your email" pattern="[^ @]*@[^ @]*" value="" size="22" tabindex="2" required="required">

<input type="text" name="url" id="comment-form-url" placeholder="Your website" size="22" tabindex="3" />
[/php]

As a value of placeholder we can specify a hint for user, it will appear as a text inside the input and after clicking on it will disappear.
pattern attribute allows us to specify a patter than must be followed. Here we have an example of pattern for email address.

HTML5 is powerful tool, but it’s not completely supported by all browsers.
More cool features we can find on http://html5demos.com/

 

Wordpress Dynamic Favicon

It’s simple to add your own link within the header.php file to create a favicon. However if you’d like to be a little more dynamic we can write a simple function inside our functions.php which adds our favicon into every page without fail. Below is the few lines of code required.

[php]
<code>function blog_favicon() {
echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.get_bloginfo('wpurl').'/favicon.ico" />';
}
add_action('wp_head', 'blog_favicon');</code>

[/php]

Custom Admin Footer Text

At the same time you may wish to edit the footer text inside your admin panel. For those who run large blogs and magazines online branding is very important. This bit of code can be added into your functions.php along with the admin panel edits above.
[php]

function remove_footer_admin () {
echo 'Skyje is Awesome. Thank you <a href="http://wordpress.org">WordPress</a> for giving me this filter.';
}
add_filter('admin_footer_text', 'remove_footer_admin');

[/php]

Wordpress Change Admin Logo

We have all seen the classic WordPress symbolism within the admin panel. Well with this bit of functionality inside your functions.php file it’s easy to build custom branding! Just be sure to upload admin_logo.png into your templates’ images folder.

[php]
function custom_admin_logo() {
echo '<style type="text/css">
#header-logo { background-image: url('.get_bloginfo('template_directory').'/images/admin_logo.png) !important; }
</style>';
}
add_action('admin_head', 'custom_admin_logo');
[/php]

Wordpress Post Autosave Limit

Wordpress auto save post help's the user to save post automatically, but you can play with it, you can set the limit of time to save the post.
Just copy the following code to your wp-config.php file

[php]
# Autosave interval set to 5 Minutes #
define('AUTOSAVE_INTERVAL', 300);
[/php]

Best way to include JQuery | Correct way to include JQuery

JQuery is the javascript library, but just copy pasting the JQuery snippet will not do, it will start conflicting with other JQeries, so the best practice is to use the following method

[php]<?php wp_enqueue_script("jquery"); ?>[/php]

Browser Caching with .htaccess

Is your site very slow, then why not you use caching? just copy the below snippet to your .htaccess file

[php]## EXPIRES CACHING ##
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
## EXPIRES CACHING ##[/php]

How to show a message in the WordPress Admin

If you are working on a plugin or a theme, and you want to display some message to the user like "Settings have been saved" or "Plugin installed, Please goto settings page to configure it", then just follow the below snippet.

[php]
/**
* Generic function to show a message to the user using WP's
* standard CSS classes to make use of the already-defined
* message colour scheme.
*
* @param $message The message you want to tell the user.
* @param $errormsg If true, the message is an error, so use
* the red message style. If false, the message is a status
* message, so use the yellow information message style.
*/
function showMessage($message, $errormsg = false)
{
if ($errormsg) {
echo '<div id="message" class="error">';
}
else {
echo '<div id="message" class="updated fade">';
}

echo "<p><strong>$message</strong></p></div>";
}
[/php]
Now we just add a hook to the admin notices function to show our custom message.

[php]
/**
* Just show our message (with possible checking if we only want
* to show message to certain users.
*/
function showAdminMessages()
{
// Shows as an error message. You could add a link to the right page if you wanted.
showMessage("You need to upgrade your database as soon as possible...", true);

// Only show to admins
if (user_can('manage_options') {
showMessage("Hello admins!");
}
}

/**
* Call showAdminMessages() when showing other admin
* messages. The message only gets shown in the admin
* area, but not on the frontend of your WordPress site.
*/
add_action('admin_notices', 'showAdminMessages');[/php]

Done.....

Add links to WordPress admin bar

So if you want custom links on your admin bar, then just copy the following code to your function.php file.
You can modify the code as per your need.

[php]
function mytheme_admin_bar_render() {
global $wp_admin_bar;
$wp_admin_bar->add_menu( array(
'parent' => 'new-content', // use 'false' for a root menu, or pass the ID of the parent menu
'id' => 'new_media', // link ID, defaults to a sanitized title value
'title' => __('Media'), // link title
'href' => admin_url( 'media-new.php'), // name of file
'meta' => false // array of any of the following options: array( 'html' => '', 'class' => '', 'onclick' => '', target => '', title => '' );
));
}
add_action( 'wp_before_admin_bar_render', 'mytheme_admin_bar_render' );[/php]

Wordpress Disable Theme Changing

So you want that your client should not change the theme. OK, just copy the following snippet to your functions.php file.

[php]
add_action('admin_init', 'slt_lock_theme');
function slt_lock_theme() {
global $submenu, $userdata;
get_currentuserinfo();
if ($userdata-&gt;ID != 1) {
unset($submenu['themes.php'][5]);
unset($submenu['themes.php'][15]);
}
}[/php]

Once saved, your client will not be able to switch or change themes anymore.

Get how many posts are returned by a custom loop

To get the output, just paste the following snippet anywhere in your themes file.

[php]
$feat_loop = new WP_Query( 'showposts=12&amp;category_name=featured' );
echo "Query returned ".$feat_loop-&gt;post_count." posts.";
[/php]

Wordpress Maintenance Mode

OK, so you want your site to be in maintenance mode, ok, no worries, just copy the following snippet to your functions.php file.

[php]

function wp_maintenance_state() { if ( !current_user_can( 'edit_themes' ) || !is_user_logged_in() ) { wp_die('This site is under maintenance. Please try later.'); } } add_action('get_header', 'wp_maintenance_state');

[/php]
Don't Forget to remove this code, once you want the site to be live.

How to remove the “read more” jump

Copy the following code to your functionss.php file.

[php]function wdc_no_more_jumping($post) {
return '<a href="'.get_permalink($post->ID).'" class="read-more">'.'Continue Reading'.'</a>';
}
add_filter('excerpt_more', 'wdc_no_more_jumping');
[/php]

Top 10 PHP snippets

Simple page caching using PHP


Implementing page cache on a website is the best thing to speed up the site. Using this function will help getting the page cache work.
[php]
<?php
// define the path and name of cached file
$cachefile = 'cached-files/'.date('M-d-Y').'.php';
// define how long we want to keep the file in seconds. I set mine to 5 hours.
$cachetime = 18000;
// Check if the cached file is still fresh. If it is, serve it up and exit.
if (file_exists($cachefile) &amp;&amp; time() - $cachetime <filemtime($cachefile)) {
include($cachefile);
exit;
}
// if there is either no file OR the file to too old, render the page and capture the HTML.
ob_start();
?>
<html>
output all your html here.
</html>
<?php
// We're done! Save the cached content to a file
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
// finally send browser output
ob_end_flush();
?>[/php]



How to Calculate distance measurement in PHP


This Function will calculate distance from one point to another using longitudes and latitudes. This function returns the output in miles, kilometers, or nautical miles.

[php]function distance($lat1, $lon1, $lat2, $lon2, $unit) {

$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);

if ($unit == "K") {
return ($miles * 1.609344);
} else if ($unit == "N") {
return ($miles * 0.8684);
} else {
return $miles;
}
}[/php]
Usage:
[php]echo distance(32.9697, -96.80322, 29.46786, -98.53506, "k")." kilometers";[/php]


Conversion of  seconds into time (years, months, days, hours…)


Following function will convert seconds into years, months, days, hours.
[php]function Sec2Time($time){
if(is_numeric($time)){
$value = array(
"years" =>0, "days" => 0, "hours" => 0,
"minutes" => 0, "seconds" => 0,
);
if($time >= 31556926){
$value["years"] = floor($time/31556926);
$time = ($time%31556926);
}
if($time >= 86400){
$value["days"] = floor($time/86400);
$time = ($time%86400);
}
if($time >= 3600){
$value["hours"] = floor($time/3600);
$time = ($time%3600);
}
if($time >= 60){
$value["minutes"] = floor($time/60);
$time = ($time%60);
}
$value["seconds"] = floor($time);
return (array) $value;
}else{
return (bool) FALSE;
}
}[/php]


Force a file to download


Use PHP to force a file to download.
Use the following function for that.
[php]function downloadFile($file){
$file_name = $file;
$mime = 'application/force-download';
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
readfile($file_name); // push it out
exit();
}[/php]


Using Google API, get whether stats.



Get the current whether information of your city or any other, using Google API. In the code below, edit the line 1 code, and replace address with your desire location.
[php]$xml = simplexml_load_file('http://www.google.com/ig/api?weather=ADDRESS');
$information = $xml->xpath("/xml_api_reply/weather/current_conditions/condition");
echo $information[0]->attributes();[/php]


Create a basic PHP WHOIS



WHOIS service is used to get the details of a domain name, domain owner, creation date, registrar etc. WIth the help of PHP and whois unix, it is extremely easy to get the function working.
REMEMBER:the WHOIS unix command must be installed on your website server for getting this code to work.
[php]$domains = array('home.pl', 'w3c.org');

function creation_date($domain) {
$lines = explode("\n", `whois $domain`);
foreach($lines as $line) {
if(strpos(strtolower($line), 'created') !== false) {
return $line;
}
}

return false;
}

foreach($domains as $d) {
echo creation_date($d) . "\n";
}[/php]



Again using Google API to get the longitude and latitude of an area.



Just follow the below function for getting the Latitude and longitude.
[php]function getLatLong($address){
if (!is_string($address))die("All Addresses must be passed as a string");
$_url = sprintf('http://maps.google.com/maps?output=js&amp;q=%s',rawurlencode($address));
$_result = false;
if($_result = file_get_contents($_url)) {
if(strpos($_result,'errortips') >1 || strpos($_result,'Did you mean:') !== false) return false;
preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U', $_result, $_match);
$_coords['lat'] = $_match[1];
$_coords['long'] = $_match[2];
}
return $_coords;
}[/php]


Get the favicon of a domain by using simple PHP and Google



[php]function get_favicon($url){
$url = str_replace("http://",'',$url);
return "http://www.google.com/s2/favicons?domain=".$url;
}[/php]


How to Calculate Paypal fees?



Want to calculate your paypal fees? then use the below function
[php]function paypalFees($sub_total, $round_fee) {

// Set Fee Rate Variables
$fee_percent = '3.4'; // Paypal's percentage rate per transaction (3.4% in UK)
$fee_cash = '0.20'; // Paypal's set cash amount per transaction (£0.20 in UK)

// Calculate Fees
$paypal_fee = ((($sub_total / 100) * $fee_percent) + $fee_cash);

if ($round_fee == true) {
$paypal_fee = ceil($paypal_fee);
}

// Calculate Grand Total
$grand_total = ($sub_total + $paypal_fee);

// Tidy Up Numbers
$sub_total = number_format($sub_total, 2, '.', ',');
$paypal_fee = number_format($paypal_fee, 2, '.', ',');
$grand_total = number_format($grand_total, 2, '.', ',');

// Return Array
return array('grand_total'=>$grand_total, 'paypal_fee'=>$paypal_fee, 'sub_total'=>$sub_total);
}
<?php
// define the path and name of cached file
$cachefile = 'cached-files/'.date('M-d-Y').'.php';
// define how long we want to keep the file in seconds. I set mine to 5 hours.
$cachetime = 18000;
// Check if the cached file is still fresh. If it is, serve it up and exit.
if (file_exists($cachefile) &amp;&amp; time() - $cachetime <filemtime($cachefile)) {
include($cachefile);
exit;
}
// if there is either no file OR the file to too old, render the page and capture the HTML.
ob_start();
?>
<html>
output all your html here.
</html>
<?php
// We're done! Save the cached content to a file
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
// finally send browser output
ob_end_flush();
?>[/php]

Jul 7, 2011

How To Add Simple Pagination To WordPress

Many sites uses pagination to navigate to the older posts. If you install twenty ten or twenty eleven default wp theme, then you will notice that instead of pagination, it gives you old fashion links.
So to have pagination write the below function to your functions.php file

 

[php]function paginate() {
global $wp_query, $wp_rewrite;
$wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;

$pagination = array(
'base' => @add_query_arg('page','%#%'),
'format' => '',
'total' => $wp_query->max_num_pages,
'current' => $current,
'show_all' =>true,
'type' =>'list',
'next_text' => '»',
'prev_text' =>'«'
);

if( $wp_rewrite->sing_permalinks() )
$pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ) . 'page/%#%/', 'paged' );

if( !empty($wp_query->query_vars['s']) )
$pagination['add_args'] = array( 's' => get_query_var( 's' ) );

echo paginate_links( $pagination );
}[/php]

After some PHP code, we will need to add some CSS styling, so it gets the looks of actual pagination.
So add the following CSS code to your style.css file

 

[php]/* Pagination */

ul.page-numbers {
margin: 20px 0 10px;
width: 100%;
padding: 0;
font-size: 12px;
line-height: normal;
clear: both;
float: left;
}

ul.page-numbers li {
float: left;
}

ul.page-numbers a,
ul.page-numbers span {
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
background: -webkit-gradient(linear, left top, left bottom, from(#E4E3E3), to(#FFFFFF));
background: -moz-linear-gradient(top, #E4E3E3, #FFFFFF);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E4E3E3', endColorstr='#FFFFFF');
padding: 3px 4px 2px 4px;
margin: 2px;
text-decoration: none;
border: 1px solid #ccc;
color: #666;
}

ul.page-numbers a:hover,
ul.page-numbers span.current {
border: 1px solid #666;
color: #444;
}[/php]

The above CSS is really simple, if you want to make your pagination to match your theme, then simply edit the CSS. Its damn Simple.
To include the pagination, we need to call the function.
So if you are going to display the pagination on the home dynamic page, then goto index.php file, and replace the below function with your old boring pagination.

[php]
<?php paginate(); ?>
[/php]

To know more about paginate_links()
Refer the Codex: http://codex.wordpress.org/Function_Reference/paginate_links

Wordpress Search URL Rewrite

Have you ever considered your wp-site search URL?

http://yoursite.com/?s=searchterm

Also after setting the custom permalink structure, the only URL which is not effected is the search URL, it still remains the same.
OK, now goto your site, and after your root URL, just type this search/term

http://yoursite.com/search/term

Woila!!!! you'll find that the search worked, just that there is no URL rewrite rule written for this.
So to make it done, just add the following function to your themes functions.php file

[php]
function search_url_rewrite_rule() {
if ( is_search() && !empty($_GET['s'])) {
wp_redirect(home_url("/search/") . urlencode(get_query_var('s')));
exit();
}
}
add_action('template_redirect', 'search_url_rewrite_rule');=
[/php]


This function will now rewrite every search results URL. Which will something look like this:-

http://yoursite.com/search/term

I have just implemented this technique on Webs Tutorial.

Wordpress plugin directory problem

Some of you may not be aware of this, but there was a small security breach in the WordPress.org plugin directory this week. Someone managed to commit malicious changes to some popular plugins by hacking into the SVN repository. The WP crew discovered the changes and managed to revert the affected plugins back to the last legitimate release. They have also shut down access to the repo to make sure no other plugins were affected.

You can read more about in the WP blog: http://wordpress.org/news/2011/06/passwords-reset/

Strange enough, the plugin we were going to review this week, BackWPup has been removed completely from the repo. After doing a bit of research it seems like there was a little issue with the plugin causing excessively long processes while backing up WP and the author is aware and working on a fix.

You can read more about that in the support forum: http://wordpress.org/support/topic/plugin-backwpup-run-away-backup-process

If the plugin is updated and works well enough, we will do another review and post about it, but for now, this weeks plugin review will be replaced with this article about the few plugins that were affected by the repo hack.

So if you are using WP Touch, W3 Total Cache or Add This make sure to update again to the most recent release which is the clean one. Also, if you are a member of WP.org, you will have to reset your password as a “prophylactic measure” to help heighten security.

How to Remove Images from a WordPress Post

This is a simple way to remove images from wordpress post. just add this piece of code.
[php]<?php
function remove_images( $content ) {
$postOutput = preg_replace('/<img[^>]+./','', $content);
return $postOutput;
}
add_filter( 'the_content', 'remove_images', 100 );
?>[/php]
If you include this in your functions.php it will remove every image from the content everywhere the_content() function has been used. That isn’t probably what you want, but what you can do is include this function in a specific page template, such as your index.php file, and then at the end of that file include the following to remove the filter:

[php]
<?php remove_filter( 'the_content', 'remove_images' ); ?>

[/php]

Jul 6, 2011

Add Sidebar to TwentyEleven Theme

This Monday WordPress released its new version, WP 3.2, with a brand new HTML5 default theme, Twenty Eleven.
But after activating this theme, you will find that the sidebar from pages and posts pages .i.e. single.php is missing,

This theme by default doesn't has sidebar in pages and posts.

To add them install Twenty Eleven Child Theme.
With this you will be able to add widgets on sinle.php or Posts page.

Download Twenty Ten Child Theme

[download id="2"]

 

Please Download the new Child Theme, which Activates Sidebar on Posts and also on Pages

Jul 5, 2011

Whats new in Wordpress 3.2 | What is wordpress 3.2

WordPress being  an open source blog tool and publishing platform powered by PHP and MySQL has always put in efforts to serve the best and advanced features to users for their ease and competency and the past few months is not a joke with the WordPress3.2.
With the release of wordpress 3.1 with a surprise after a couple of months comes wordpress 3.2 with more advanced features enhancing user experience.  The wordpress community is growing rapidly and the apex of it being the release of wordpress 3.2 which is the 15th major release of wordpress.
"WordPress 3.2 contain various new and inspiring updates which will make WordPress more lighter and faster than ever before."
-Mark Jaquith

Wordpress 3.2 key features/highlights

  • New Dashboard View


dashboard




  • New Themes View


theme-view




  • New Menu View


menu-view




  • New Widget View


widgets-view




  • New Plugins View


plugins-view




  • New Post View


new-post-view




  • Distraction Free Writing


Distraction Free Writing is another major update to the WordPress 3.2 writing interface for quite some time. The writing interface of WordPress 3.1 was cleaned up a bit by hiding Meta Box (Custom Fields, Author, etc) by default. So you can just focus on the content by using Distraction Free Writing feature. The aim to introduce Distraction Free Writing is to make the writing experience faster, calming and lightweight.


distraction-free-writing




  • Speedy Improvements


Use of large database can stop a website in wordpress. Although WP provides continuous support to some old technology in the core files which wont be availbe in WP3.2, making it load faster.


Research still going on by NAcin to make the admin load faster along with FTP improvement which upgrades faster by expansion in php.




  • Auto Upgrading Improvements


Improved Upgrading feature is another core feature of WordPress 3.2. The developers are focusing more on upgrading only the changed (updated) files instead of entire package.




  • New Theme – Twenty Eleven


And guess what, with the version release, new default theme has been release with this version, i.e Twenty Eleven. Twenty Eleven  is fully made in HTML5, and got more useful features.


twenty-eleven



If you want to upgrade to WordPress 3.2 do make sure your hosting provider is using PHP5 and MYSQL5 technology.

So don't wait, Wordpress 3.2 is officially released, so just go and download it.

For more features see the below video
httpv://www.youtube.com/watch?v=N3PbAxX1OsM

Jul 3, 2011

Centos Virtual hosting | Enabling multi apache hosting through 1 IP

OK, so now you decided to have one VPS, one IP, and many sites?
Cool, its very easy

First in the root folder, create your website folders, like you have 2 websites, so name them as site1.com and site2.com

So now you'll be having two website folders site1.com and site2.com in your root directory.

Now navigate to /etc/httpd/conf/ and start editing httpd.conf file,

At the end of the page, you will find a line, just like below

#NameVirtualHost *:80

Just uncomment that by removing # from it, So that it becomes like the below one:-

NameVirtualHost *:80

Then below their will be more lines which will be commented so uncomment them also, and make them look something like this

[php]
<VirtualHost *:80>
ServerAdmin webmaster@dummy-host.example.com
DocumentRoot /var/www/html/site1.com
ServerName site1.com
ErrorLog logs/site1-error_log
CustomLog logs/site1-access_log common
</VirtualHost>

<VirtualHost *:80>
ServerAdmin webmaster@dummy-host.example.com
DocumentRoot /var/www/html/site2.com
ServerName site2.com
ErrorLog logs/site2-error_log
CustomLog logs/site2-access_log common
</VirtualHost>
[/php]

Thats it, after this just restart your apache by the following command

[php]
service httpd restart
[/php]

Done,
You have successfully enabled multi-site or virtual hosting on apache Centos.

How to enable mod_rewrite in centos via SSH

This is a very simple question, but for beginners it is little bit difficult,
Now assuming that everything is installed, open the httpd conf file and start editing it,

You can find this file in

/etc/httpd/conf/httpd.conf

or directly edit it

[php]vi /etc/httpd/conf/httpd.conf[/php]
in this file search for Directory "/var/www/html" this can be on line 290-320

You will find a line of code, just like below

[php]AllowOveride None[/php]

Just change it to

[php]AllowOverideAll[/php]

Save it, and exit, mod_rewrite is enabled on your server.