WP-HELP Index
BLOG iNFO
1
<?php bloginfo('template_directory')?> 
<?php bloginfo('url')?> 
<?php bloginfo('template_directory')?> 
<ul>
<?php wp_list_categories('title_li=&child_of=3&show_count=1'); ?>
</ul> 

CODE Inside Loop
2
<?php the_permalink() ?>
 - This will echo the permalink of the post, i.e http://www.themelab.com/?p=1 
<?php the_title(); ?> 
- This echos the post title, i.e. Hello World!
 <?php the_time(’F jSY’?> - This will echo the date, i.e. April 4th, 2008. A full list of ways to format the date can be found on php.net
 <?php the_author() ?> 
- This will display the author’s name, i.e. Leland. This is commented out in the default theme. 
<?php the_tags(’Tags‘‘‘‘<br />’); ?> 
- This will display the tags assigned to the post, separated by commas, and followed by a line break 
<?php the_category(’‘?> 
 - This will display the categories in a similar fashion as the tags above. 
<?php edit_post_link(’Edit’â€?, â€˜ â€˜); ?>  
- The edit post link will be visible only to those with permission.
 <?php comments_popup_link(’No Comments Â»â€™â€˜1 Comment Â»â€™â€˜Comments Â»â€™); ?> 
 - Will display the link to the comments. This will not be displayed on single posts or pages. 

Min Hight In IE6
3
min-height:350px; 
_height:350px; 

Excerpt
4
<?php echo substr(get_the_excerpt(),0,110).'....'?>
<?php the_excerpt_reloaded
(15'''none'false''false1,true); ?> // =>Work only with Excerpt_Reloaded plugin.
<?php the_excerpt_reloaded('15'); ?>  

Current Year PHP
5
<?php echo date('Y'?>

Browser List
6
Fire Fox 3.0.7
Fire Fox 3.0.13
Fire Fox 3.5.5
IE-6,7,8
Opera
Chrome
Safari
Netscape Navigator

Display Subpage of a Parentpage
7
<?php
if($post->post_parent)
$children wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
else 
$children wp_list_pages("title_li=&child_of=".$post->ID."&echo=0&depth=1");
 if (
$children) { ?>  
<ul><?php echo $children?>  
</ul><?php 

?> 

Retrieving custom fields outside the loop
8
<?php global $wp_query;
$postid $wp_query->post->ID;

echo 
get_post_meta($postid'customField'true);
// <== 'customField'=Custom field name ?> 

Implementing New Style Sheet For IE6
9
Add to header 
<!--[if IE 6]> 
<link href="<?php bloginfo('template_directory')?>/ie.css" rel="stylesheet" type="text/css" />  
<![endif]-->  

Bookmakify plugin inside Loop
10
<?php bookmarkifyIt(the_title('','',false), get_permalink(), true); ?> 

Number of your Twitter followers on your WordPress blog
11
Function -------- function string_getInsertedString($long_string,$short_string,$is_html=false)
{ if($short_string>=strlen($long_string))
return false; $insertion_length=strlen($long_string)-strlen($short_string);
for($i=0;$i<strlen($short_string);++$i)

if($long_string[$i]!=$short_string[$i])
break; 

$inserted_string=substr($long_string,$i,$insertion_length); 
if($is_html && $inserted_string[$insertion_length-1]=='<')
{ $inserted_string='<'.substr($inserted_string,0,$insertion_length-1);
 } return $inserted_string; 

function DOMElement_getOuterHTML($document,$element)
{
$html=$document->saveHTML(); $element->parentNode->removeChild($element); $html2=$document->saveHTML(); 
return string_getInsertedString($html,$html2,true);
 } 
function getFollowers($username)

$x = file_get_contents("http://twitter.com/".$username); $doc = new DomDocument; @$doc->loadHTML($x); $ele = $doc->getElementById('follower_count');

$innerHTML=preg_replace('/^<[^>]*>(.*)<[^>]*>$/',"\1",DOMElement_getOuterHTML($doc,$ele)); return $innerHTML;
 } 

Template Code ------------- 
<?php 
echo getFollowers("hasanulbanna")." followers"
?> 

XHTML Valid Flash Embed
12
<object type="application/x-shockwave-flash" data="http://192.168.1.30/mfit/mfitblogbanners/250x250_MDC-3.swf" width="250" height="250">

<param name="movie" value="http://192.168.1.30/mfit/mfitblogbanners/250x250_MDC-3.swf" />
 
<param name="quality" value="high"/>  
</object>  

Category Specific Loop // Cat=>11 No# Post=>5
13
<?php query_posts('cat=11&showposts=5'); ?>
<?php 
while (have_posts()) : the_post(); ?>
<a href="<?php echo get_permalink() ?>">
<?php the_title(); ?></a>
<?php the_content(); ?>
<?php 
endwhile; ?>
<?php wp_reset_query
();?>

Pagination with query
14
<?php
    
global $paged;
    if(!
$paged) {
        
query_posts('cat=5');
    }else {
        
query_posts('cat=5&paged=' $paged);
    }
?>

Give Readmore link to [...] along with the_excerpt function
15
function excerpt_ellipse($text) {
   return str_replace('[...]', ' <a href="'.get_permalink().'">[...]</a>', $text); }
add_filter('the_excerpt', 'excerpt_ellipse');

Footer Tweak
16
<div class="footer_menu">
        <ul>
            <li><a href="<?php echo get_option('home'); ?>/">Home</a></li>
             <?php wp_list_pages('title_li=&exclude=12' ); ?>
             <?php
                 $page_id
=12;
                 
$page_data get_page($page_id);
                 
$title $page_data->post_title;
             
?>
            <li style="border:none;"><a href="<?php echo(get_page_link(12)); ?>"><?php echo $title?></a></li>
            
        </ul>
        <div class="clear"></div>
    </div>
    
    <div class="footer_copy">Copyright &copy; <?php echo date('Y'?> <?php bloginfo('name')?></div>

Change the default Excerpt
17
function excerpt_binoy($text) {
   return str_replace('[...]', '<a class="more" href="'.get_permalink().'">more...</a>', $text); }
add_filter('get_the_excerpt', 'excerpt_ellipse');

/*Calling the function*/

<?php echo substr(get_the_excerpt(),0,700); ?>

Substring WP Title
18
<h1><a href="<?php echo get_permalink() ?>">
<?php 
$title_temp
=the_title('','',false);
if(
strlen($title_temp) > 30) {
$title_temp substr($title_temp030) . '...';

echo 
$title_temp;
?></a></h1>

Custom Fields Manipulation
19
<?php $image get_post_meta($post->ID'image'true); ?>
<?php  
if($image!='')
    {
?>
        <a href="<?php the_permalink() ?> ">
        <img width="185" height="220" src="<?php echo $image ?>" class="finalist_image" alt="<?php the_title(); ?>" />
        </a>
                   
    <?php } else {?>
             
        <a href="<?php the_permalink() ?> ">
        <img width="185" height="220" src="<?php bloginfo('template_directory')?>/images/shadowgirl.jpg" class="finalist_image" alt="<?php the_title(); ?>" />
        </a>
             
        <?php }?>

How To Display Your Twitter Status
20
<div id="twitter">
<h1>
<a href="http://twitter.com/line25blog">@line25blog</a></h1>
<ul id="twitter_update_list"></ul>
</div>
<script src="http://twitter.com/javascripts/blogger.js" type="text/javascript"></script>
<script src="http://twitter.com/statuses/user_timeline/line25blog.json?callback=twitterCallback2&count=1" type="text/javascript"></script>

Source:
-------
http://line25.com/tutorials/how-to-display-your-twitter-status-in-a-unique-design

Tims Feris Blog Twitter Feed
21
Tuts Source:
------------
http://www.maverickwebcreations.com/2008/11/06/twitter-status-message-speech-bubble-wordpress.html

IE PNG Fix .HTC file
22


behavior: url(http://192.168.1.19/laura/wp-content/themes/lauratheme/iepngfix.htc);

Define Sidebar
23
if ( function_exists('register_sidebar') )
    register_sidebar(array(
        'name' => 'Footer-Area',
        'before_widget' => '',
        'after_widget' => '',
        'before_title' => '',
        'after_title' => '',
    ));

-------
Calling
-------
<?php dynamic_sidebar('Footer-Area'?> 

To make the flash swf transparent.
24
On the flash(swf) embed code, add the following param.

<param name="wmode" value="transparent" />

The it will display the text above the flash object.

Solution to Dropdown menu behind youtube video
25
Add param 
<param name="wmode" value="opaque"></param>
with the code

Add wmode="opaque" along with <embed ...

Eg:
<embed src="http://www.youtube.com/v/bilOOPuAvTY&hl=en_US&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="346" height="255" wmode="opaque"></embed>

jQuery.noConflict Mode
26
<script type="text/javascript">
var SWNS = jQuery.noConflict();
     SWNS(function(){
        SWNS("ul#tabs > li").hover(
        function(){
            SWNS('ul', this).show();
        },
        function(){
            SWNS('ul', this).hide();
        }
        );
    });
</script>

Set Up Custom Wordpress post Templates
27
<?php
$post 
$wp_query->post;
if ( 
in_category('13') ) {
include(
TEMPLATEPATH '/single13.php');
} else {
include(
TEMPLATEPATH '/single1.php');
}
?>

Posts from current category
28
<?php global $post;
    
$categories get_the_category($post->ID);
    
$cat_attr='';
    foreach(
$categories as $categorieobj) {
    if (
$cat_attr == ''){
        
$cat_attr $categorieobj->cat_ID;
    } else {
        
$cat_attr ',' $categorieobj->cat_ID;
    }    
    
    }
    
$cat_attr 'cat=' $cat_attr;
    
query_posts($cat_attr '&showposts=3&orderby=date&order=DESC' );
    while (
have_posts()) : the_post(); ?>
        <p><a href="<?php echo get_permalink() ?>"> <?php the_title(); ?></a></p>
    <?php endwhile; 
     
wp_reset_query();
}
?>

WP Default Thumbnail 2.9
29
Functions:
=========
add_theme_support('post-thumbnails');
set_post_thumbnail_size( 190,140,true );
add_image_size('sw_thumb',50,50);

Usage:
======
<?php the_post_thumbnail(); ?>

Different Size:
<?php the_post_thumbnail('sw_thumb'); ?> 

Footer area
30
Copyright &copy; <?php echo date('Y'?> <?php bloginfo('name')?>

Gravatar icon with comment
31
<div class="gravs">
<?php if (get_bloginfo('version')>=2.9)
echo 
get_avatar$comment->comment_author_email$size '50'$comment->comment_author_link);?>
</div>

Excerpt Limit change
32
function new_excerpt_length($length) {
    return 20;
}
add_filter('excerpt_length', 'new_excerpt_length');

Custom Filed Manipulation New With checking
33
<?php $app_date get_post_meta($post->ID'app_date'true); ?> 
<?php  if(($app_date!='') && (isset($app_date))){?>
                
        <h3 class="appea_date">
       <?php echo $app_date?>
        </h3>
  <?php }?>
  

Get Page name by ID
34
<?php $pageID 86$page get_post($pageID); echo $page->post_title?>

Adding a Tag to a content using JQ.
35
$(document).ready(function(){
      $(".contact_field_infos span label span").each(function (i) {
            var content = $(this).html();
            content = content + "<br/>";
            $(this).html(content);
      });


 }); 

Edit default Excerpt (Wordpress 2.9x)
36
function new_excerpt_more($more) {
    return '<a href="'.get_permalink().'">...&nbsp;Read&nbsp;More</a>';
}

add_filter('excerpt_more', 'new_excerpt_more');

/*-----To edit the excerpt length----*/

function new_excerpt_length($length) {
    return 150;
}
add_filter('excerpt_length', 'new_excerpt_length'); 

Sidebar Navigation with Subpage and Parent menu
37
<?php if ( is_page() ) { ?>

<?php
if($post->post_parent)
$children wp_list_pages('title_li=&child_of='.$post->post_parent.'&echo=0'); else
$children wp_list_pages('title_li=&child_of='.$post->ID.'&echo=0');
if (
$children) { ?>

<li>
<h2>
<?php
$parent_title 
get_the_title($post->post_parent);
echo 
$parent_title;
?>
</h2>

<ul>
<?php echo $children?>
</ul>
</li>

<?php } } ?>

Improving WordPress the_excerpt() template tag ( Allow excerpt to display HTML tag)
38
function improved_trim_excerpt($text) {
    global $post;
    if ( '' == $text ) {
        $text = get_the_content('');
        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]&gt;', $text);
        $text = preg_replace('@<script[^>]*?>.*?</script>@si', '', $text);
        $text = strip_tags($text, '<p>');
        $excerpt_length = 80;
        $words = explode(' ', $text, $excerpt_length + 1);
        if (count($words)> $excerpt_length) {
            array_pop($words);
            array_push($words, '[...]');
            $text = implode(' ', $words);
        }
    }
    return $text;
}

remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'improved_trim_excerpt');

Make *ALL* Wordpress Categories use their Parent Category Template
39
function myTemplateSelect()
{
    if (is_category()) {
        if (is_category(get_cat_id('brands')) || cat_is_ancestor_of(get_cat_id('brands'), get_query_var('cat'))) {
            load_template(TEMPLATEPATH . '/category-brands.php');
            exit;
        }
    }
}
add_action('template_redirect', 'myTemplateSelect');

Custom Post Type Wordpress 3.0+
40
Function
=======
<?php
add_action
('init''my_custom_init');
function 
my_custom_init() 
{
  
$labels = array(
    
'name' => _x('News''post type general name'),
    
'singular_name' => _x('News''post type singular name'),
    
'add_new' => _x('Add New''news'),
    
'add_new_item' => __('Add New News'),
    
'edit_item' => __('Edit News'),
    
'new_item' => __('New News'),
    
'view_item' => __('View News'),
    
'search_items' => __('Search News'),
    
'not_found' =>  __('No news found'),
    
'not_found_in_trash' => __('No news found in Trash'), 
    
'parent_item_colon' => ''
  
);
  
$args = array(
    
'labels' => $labels,
    
'public' => true,
    
'publicly_queryable' => true,
    
'show_ui' => true
    
'query_var' => true,
    
'rewrite' => true,
    
'capability_type' => 'post',
    
'hierarchical' => false,
    
'menu_position' => null,
    
'supports' => array('title','editor','thumbnail')
  ); 
  
register_post_type('news',$args);
}

?>
Using with template
===================
query_posts('post_type=news');

Read Images from folder
41
 
<?php

$string
="";
$filePath=dirname(__FILE__) . "/banner/"# Specify the path you want to look in. 
$dir opendir($filePath); # Open the path
while ($file readdir($dir)) { 
  if (
eregi("\.jpg",$file) || eregi("\.jpeg",$file)) { # Look at only files with a .jpg or .jpeg extension

?>
    <img src="<?php bloginfo('template_directory')?>/banner/<?php echo $file?>" alt="Slideshow Image" class="active" />

<?php
      
  
}
}

?>   


===========================================
put this code within the division , where the images to come

Post With Category Navigation.
42
<?php
function fb_posts_by_category() {
    global 
$wpdb$post;
 
    
$mylimit '-1'// limit for posts, -1 for all
    
$sort_code 'ORDER BY name ASC, post_date DESC';
    
$the_output '';
 
    
$last_posts = (array)$wpdb->get_results("
        SELECT 
$wpdb->terms.name, $wpdb->terms.term_id
        FROM 
$wpdb->terms$wpdb->term_taxonomy
        WHERE 
$wpdb->terms.term_id = $wpdb->term_taxonomy.term_id
        AND 
$wpdb->term_taxonomy.taxonomy = 'category'
        
{$hide_check} 
    "
);
 
    if ( empty(
$last_posts) )
        return 
NULL;
 
    
$used_cats = array();
    
$i 0;
    foreach (
$last_posts as $posts) {
        if ( 
in_array($posts->name$used_cats) ) {
            unset(
$last_posts[$i]);
        } else {
            
$used_cats[] = $posts->name;
        }
        
$i++;
    }
    
$last_posts array_values($last_posts);
 
    
//$the_output .= '<ul>';
    
foreach ($last_posts as $posts) {
        
$class 'cat-item cat-item-' $posts->term_id;
        
$catsy get_the_category();
        
$current_category $catsy[0]->cat_ID;
        if ( isset(
$current_category) && $current_category && ($posts->term_id == $current_category) )
        
$class .=  ' current-cat';
        elseif ( isset(
$_current_category) && $_current_category && ($posts->term_id == $_current_category->parent) )
        
$class .=  ' current-cat-parent';
         
        
$the_output .= '<li class="' $class '"><a class="category" href="' get_category_link($posts->term_id) . '">' apply_filters('list_cats'$posts->name$posts) . '</a>';
        
$where apply_filters('getarchives_where'"WHERE post_type = 'post' AND post_status = 'publish'" $r );
 
        if (
'-1' !== $mylimit)
            
$limit ' LIMIT ' . (int) $mylimit;
        else
            
$limit '';
 
        
$arcresults $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' AND ID IN (Select object_id FROM $wpdb->term_relationships$wpdb->terms WHERE $wpdb->term_relationships.term_taxonomy_id =" $posts->term_id ") ORDER BY post_date DESC$limit");
        if (isset(
$arcresults) && $arcresults) {
            
$the_output .= '<ul>';
            foreach ( 
$arcresults as $arcresult ) {
                
$class 'post-item post-item-' $arcresult->ID;
                
$current_post get_the_ID();
                if ( isset(
$current_post) && $current_post && is_singular() && ($arcresult->ID == $current_post) )
                
$class .=  ' current-post';
 
                
$the_output .= '<li class="' $class '"><a class="post" href="' get_permalink($arcresult->ID) . '">' apply_filters('the_title'$arcresult->post_title) . '</a></li>';
            }
            
$the_output .= '<li><a href="'.get_category_link($posts->term_id).'">More...</a></li></ul>';
        }
 
        
$the_output .= '</li>';
    }
    
//$the_output .= '</ul>';
 
    
echo $the_output;
}
?>

Footer Menu With CSS
43
Markup
------
<div class="footer_menu">
        <ul>
            <li><a href="<?php echo get_option('home'); ?>/">Home</a></li>
             <?php wp_list_pages('title_li=&exclude=17' ); ?>
             <?php
                 $page_id
=17;
                 
$page_data get_page($page_id);
                 
$title $page_data->post_title;
             
?>
            <li style="border:none;"><a href="<?php echo(get_page_link(17)); ?>"><?php echo $title?></a></li>
        </ul>
        <div class="clear"></div>
        </div>

CSS
---
.footer_menu{
    margin-bottom:3px;
    }
.footer_menu ul {
    list-style-type: none;
    display: inline;
}
.footer_menu ul li {
    float: left;
    border-right-width: 1px;
    border-right-style: solid;
    border-right-color: #124f9a;
    height: 11px;
    line-height: 11px;
    margin-right: 7px;
    padding-right: 7px;
}
.footer_menu ul li a{
    font-size: 12px;
    color: #000000;
}

Add animated anchor tag to site (Java Script)
44
Define this function in header
--------------------------------
<script type='text/javascript'>

function goToByScroll(id){
         $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}

</script>

Call it wherever you want
-----------------------------
<a href="javascript:void(0)" onClick="goToByScroll('name_of_the_id')">Contact Us</a>

Using custom fields (more fields)
45
 <?php $variable_name get_post_meta($post->ID'custom_field_key'true); ?> 
                    <?php echo $var_name ?>

Display an image if flash content is not loaded
46
<SCRIPT LANGUAGE=JavaScript1.1>
<!--
var MM_contentVersion = 6;
var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
if ( plugin ) {
        var words = navigator.plugins["Shockwave Flash"].description.split(" ");
        for (var i = 0; i < words.length; ++i)
        {
        if (isNaN(parseInt(words[i])))
        continue;
        var MM_PluginVersion = words[i]; 
        }
    var MM_FlashCanPlay = MM_PluginVersion >= MM_contentVersion;
}
else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 
   && (navigator.appVersion.indexOf("Win") != -1)) {
    document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n'); //FS hide this from IE4.5 Mac by splitting the tag
    document.write('on error resume next \n');
    document.write('MM_FlashCanPlay = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & MM_contentVersion)))\n');
    document.write('</SCR' + 'IPT\> \n');
}

if ( MM_FlashCanPlay ) {
    document.write('<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"');
    document.write('  codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" ');
    document.write(' ID="script" WIDTH="526" HEIGHT="244" ALIGN="">');
    document.write(' <PARAM NAME=movie VALUE="http://www.sitename.com/flash.swf" /> <PARAM NAME=quality VALUE=high />  '); 
    document.write(' <param name="wmode" value="transparent" />  '); 
    document.write(' <EMBED src="http://www.sitename.com/flash.swf" quality=high wmode="transparent" loop="false" ');
    document.write(' swLiveConnect=FALSE WIDTH="526" HEIGHT="244" NAME="script" ALIGN=""');
    document.write(' TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">');
    document.write(' </EMBED>');
    document.write(' </OBJECT>');
} else{
    document.write('<IMG SRC="http://www.sitename.com/no_flash.png" WIDTH="526" HEIGHT="244" usemap="#script" BORDER=0>');
}
//-->
</SCRIPT>
<NOSCRIPT><IMG SRC="http://www.sitename.com/no_flash.png" WIDTH="526" HEIGHT="244" usemap="#script" BORDER=0></NOSCRIPT>

Bookmark site link
47
Add this code inside <head> tag:

<script Type="text/javascript">
/* Modified To support Opera */
function bookmarksite(title,url){
if (window.sidebar) {// firefox
    window.sidebar.addPanel(title, url, "");
} else if(window.opera && window.print){ // opera
    var elem = document.createElement('a');
    elem.setAttribute('href',url);
    elem.setAttribute('title',title);
    elem.setAttribute('rel','sidebar');
    elem.click();
} else if(document.all) {// ie
    window.external.AddFavorite(url, title);
} else {
    //window.sidebar.addPanel(title, url, ""); Dont use until it's fixed
     alert('Please press CTRL+D to Bookmark this page!');
}
}
</script>


Code in body part:

<a class="bookmarker" href="javascript:bookmarksite('<?php bloginfo('name')?>', '<?php bloginfo('url')?>/')"></a>

Add a "Bookmark Site" button to the site
48
Add this code to the header
--------------------------------------------------------------
<script type="text/javascript">
/* Modified To support Opera */
function bookmarksite(title,url){
if (window.sidebar) {// firefox
    window.sidebar.addPanel(title, url, "");
} else if(window.opera && window.print){ // opera
    var elem = document.createElement('a');
    elem.setAttribute('href',url);
    elem.setAttribute('title',title);
    elem.setAttribute('rel','sidebar');
    elem.click();
} else if(document.all) {// ie
    window.external.AddFavorite(url, title);
} else {
    //window.sidebar.addPanel(title, url, ""); Dont use until it's fixed
     alert('Please press CTRL+D to Bookmark this page!');
}
}
</script>

Add this code to the template
---------------------------------------------------------
<a class="bookmarker" href="javascript:bookmarksite('<?php bloginfo('name')?>', '<?php bloginfo('url')?>/')"></a>

Get posts count from a category
49
Function:
-------------
function wt_get_category_count($input = '') {
    global $wpdb;
    if($input == '')
    {
        $category = get_the_category();
        return $category[0]->category_count;
    }
    elseif(is_numeric($input))
    {
        $SQL = "SELECT $wpdb->term_taxonomy.count FROM $wpdb->terms, $wpdb->term_taxonomy WHERE $wpdb->terms.term_id=$wpdb->term_taxonomy.term_id AND $wpdb->term_taxonomy.term_id=$input";
        return $wpdb->get_var($SQL);
    }
    else
    {
        $SQL = "SELECT $wpdb->term_taxonomy.count FROM $wpdb->terms, $wpdb->term_taxonomy WHERE $wpdb->terms.term_id=$wpdb->term_taxonomy.term_id AND $wpdb->terms.slug='$input'";
        return $wpdb->get_var($SQL);
    }
}

Calling the function:
----------------------
<?php echo wt_get_category_count(); ?>

Get category link (display posts from a certain category inside the loop)
50
<a href="<?php echo get_category_link($category)?>"><?php echo get_cat_name($category?></a>

Display tweets from your Twitter ID
51
<a class="from_twitter" href="http://www.twitter.com/your_twitter_id" target="_blank"></a> 
<div id="twitter">
<ul id="twitter_update_list"></ul>
</div>
<script src="http://twitter.com/javascripts/blogger.js" type="text/javascript"></script>
<script src="http://twitter.com/statuses/user_timeline/twitter.com/your_twitter_id.json?callback=twitterCallback2&count=3" type="text/javascript"></script>

Custom menu in Wordpress 3.0
52
Activate menu in function.php
----------------------------------

<?php
// This theme uses wp_nav_menu() in one location.  
register_nav_menus( array('my_nav' => __'Primary Navigation''sw theme' ),
'secondary' => __('Secondary Navigation''sw theme'
));
?>

Calling in template
--------------------

<div id="access"role="navigation" >
<div class="menu-header">
  <?php wp_nav_menu( array( 'container_class' => 'menu-header''theme_location' => 'my_nav' ) ); ?>
</div>
</div>

Original CSS (with the TwentyTen theme)
----------------------------------------

/* =Menu
-------------------------------------------------------------- */

#access {
    background: #000;
    margin: 0 auto;
    width: 980px;
    display:block;
    float:left;
}
#access .menu-header,
div.menu {
    font-size: 13px;
    margin-left: 12px;
}
#access .menu-header ul,
div.menu ul {
    list-style: none;
    margin: 0;
}
#access .menu-header li,
div.menu li {
    float:left;
    position: relative;
}
#access a {
    display:block;
    text-decoration:none;
    color:#aaa;
    padding:0 10px;
    line-height:38px;
}
#access ul ul {
    display:none;
    position:absolute;
    top:38px;
    left:0;
    float:left;
    box-shadow: 0px 3px 3px rgba(0,0,0,0.2);
    -moz-box-shadow: 0px 3px 3px rgba(0,0,0,0.2);
    -webkit-box-shadow: 0px 3px 3px rgba(0,0,0,0.2);
    width: 180px;
    z-index: 99999;
}
#access ul ul li {
    min-width: 180px;    
}
#access ul ul ul {
    left:100%;
    top:0;
}
#access ul ul a {
    background:#333;
    height:auto;
    line-height:1em;
    padding:10px;
    width: 160px;
}
#access li:hover > a,
#access ul ul :hover > a {
    color:#fff;
    background:#333;
}
#access ul li:hover > ul {
    display:block;
}
#access ul li.current_page_item > a,
#access ul li.current-menu-ancestor > a,
#access ul li.current-menu-item > a,
#access ul li.current-menu-parent > a {
    color: #fff;
}

* html #access ul li.current_page_item a,
* html #access ul li.current-menu-ancestor a,
* html #access ul li.current-menu-item a,
* html #access ul li.current-menu-parent a,
* html #access ul li a:hover {
    color:#fff;
}

Extract the first post from a loop
53
<?php query_posts('showposts'); ?>
    <?php if (have_posts()) : ?>
    <?php the_post(); ?> 
   <div class="post" id="post-<?php the_ID(); ?>">
        <h1 class="title"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h1>
        <p class="meta"><small>Submitted by <?php the_author() ?> on <?php the_time('D, d/m/Y - h:i'?></small></p>
        <div class="entry">
          <?php the_excerpt(''); ?>
        </div>
        
    </div>
<?php else : ?>
    <h2 class="center">Not Found</h2>
    <p class="center">Sorry, but you are looking for something that isn't here.</p>
<?php endif; ?>
    
   <p> Now the remaining posts displaying </p>
    
<?php if (have_posts()) : ?>
    <?php  while (have_posts()) : the_post(); ?> 
   <div class="post" id="post-<?php the_ID(); ?>">
        <h1 class="title"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h1>
        <p class="meta"><small>Submitted by <?php the_author() ?> on <?php the_time('D, d/m/Y - h:i'?></small></p>
        <div class="entry">
          <?php the_excerpt(''); ?>
        </div>
    </div>
<?php endwhile; ?>
<?php 
endif; ?>
<?php wp_reset_query
();?> 

Page Checking using PHP
54
To page
--------
<?php $page_template_name 'gallery'?>

To Header
---------
<?php 
global $page_template_name;
if(isset(
$page_template_name) && $page_template_name == 'gallery'
{
?>
<---- Do some Stuffs --->
<?php
}?>

Retrive more field value with checking
55
<?php $report get_post_meta($post->ID'report'true); ?> 
<?php  if(($report!='') && (isset($report))){?>
 <div class="main_title">
    <?php echo $report?>
 </div>
<?php }?> 

Creating A Shortcode
56
Function
===========

function get_short($atts) {
    return 'My Short code test';
}
add_shortcode('wpshort', 'get_short');

Usage
===========
[wpshort]

Getting rid off annoying [...] from excerpt's end.
57
function trim_excerpt($text) {
  return rtrim($text,'[...]');
}
add_filter('get_the_excerpt', 'trim_excerpt');

Custom field values in widget
58
function.php

function get_custom_field_value($szKey, $bPrint = false) {
    global $post;
    $szValue = get_post_meta($post->ID, $szKey, true);
    if ( $bPrint == false ) return $szValue; else echo $szValue;
}
function call :

<?php if ( function_exists('get_custom_field_value') ){
        
get_custom_field_value('featured_image'true);
?>

Display categories with posts
59
<ul>
 <?php
     $category_id 
explode(",",get_option('category_option_name'0));
     foreach(
$category_id as $category){?>
     <?php query_posts('cat='.$category.'&showposts=1');
     if (
have_posts()) : ?>
     <?php while (have_posts()) : the_post(); ?>
     <li>
        <div class="each_category">
            <div class="category_posts">
               <div class="category_header">
                    <h1 class="cat_title">
                        <a href="<?php echo get_category_link($category)?>"><?php echo get_cat_name($category?></a>
                    </h1>
                </div> 
                 <?php if(has_post_thumbnail()){ ?>
                    <div class="category_image">
                        <a href="<?php the_permalink() ?>"> <?php the_post_thumbnail('cat_thumb'); ?></a>
                        </div>
                <?php ?>
                <div class="latest_posts">
                    <ul> <?php global $post;
                     
$myposts get_posts('numberposts=4&cat='.$category);
                     foreach(
$myposts as $post) :
                     
setup_postdata($post); ?>
                       
                         <li>
                          <a class="latest_title" href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">
                            <?php the_title(); ?>
                          </a>
                        </li>
                      
                    <?php endforeach; ?> </ul> 
               </div>
            </div>
        </div> 
     </li>
     <?php endwhile; ?>
     <?php endif; ?>
     <?php wp_reset_query(); ?>   
    <?php ?>
</ul>

Display categories with post number (customized code for styling)
60
<ul>
  <?php
     $categories 
wp_list_categories('title_li=&show_count=1&echo=0');
     
$categories ereg_replace('</a> \(([0-9]+)\)'' <span class="count">[\\1]</span></a>'$categories);
echo 
$categories;
  
?>
</ul>

Share permalink in Facebook
61
<a class="smallfb" href="http://www.facebook.com/share.php?u=<?php the_permalink(); ?>" target="_blank">Share in facebook</a>

Contact form 7 code in template
62
<?php echo do_shortcode('[contact-form "Contact form 1"]'); ?>

Select the first letter in paragraph for styling using jQuery
63
In single.php, add a class for the entry class (eg: <div class="entry" id="singlepostentry">)

Code in header
-------------------

<script type='text/javascript'>
    $(document).ready(function(){
        $('#singlepostentry p strong:first').addClass('fbld');
    });
</script>

CSS
------------

.fbld {
    background: none repeat scroll 0 0 #FFFFFF;
    border: 3px solid #FF9818;
    color: #FF9818;
    float: left;
    font: 50px/55px Georgia,"Times New Roman",serif;
    margin: 6px 10px 0 0;
    padding: 0 15px;
    text-align: center;
}

Display a login form in the template
64
<?php if (!(current_user_can('level_0'))){ ?>

    <form action="<?php echo get_option('home'); ?>/wp-login.php" method="post">
    <input type="text" name="log" class="my_log_usps" id="log" value="<?php echo wp_specialchars(stripslashes($user_login), 1?>" size="20" />
    <br />
    <input type="password" class="my_log_usps" name="pwd" id="pwd" size="20" />
    <br />
    <input type="submit" name="submit" value="Send" class="my_log_button" />
    <br />
           <label class="remember" for="rememberme"><input name="rememberme" id="rememberme" type="checkbox" checked="checked" value="forever" /> Remember me</label>
           <input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" />
  
    </form>
    <a href="<?php echo get_option('home'); ?>/wp-login.php?action=lostpassword" class="my_rec">Recover password</a>
    <?php 

Get all the images uploaded under a page
65
Add this in functions.php
------------------------------
<?php
function get_images($size 'thumbnail') {
    global 
$post;
    return 
get_children( array('post_parent' => get_the_ID(), 'post_status' => 'inherit''post_type' => 'attachment''post_mime_type' => 'image''order' => 'ASC''orderby' => 'menu_order ID') );
?>

Add this code in template
-------------------------------
 <?php 
     $photos 
get_images('full');
if (
$photos){
        foreach (
$photos as $photo){
        echo(
'<img alt="'.$photo->post_title.'" src="'.wp_get_attachment_url($photo->ID).'" />' "\n");
     }
 } 
?>

Enable 'Custom background' option in WP 3.0
66
Add this to the function.php
-------------------------------------
add_custom_background();

Enable 'Custom header' option in WP 3.0
67
Add this to function.php
--------------------------------
add_custom_image_header('header_style', 'admin_header_style');
    define('HEADER_TEXTCOLOR', 'ffffff');
    define('HEADER_IMAGE', '%s/images/banner.jpg'); // %s is the template dir uri, define a default header banner with name banner.jpg
    define('HEADER_IMAGE_WIDTH', 980); // use width and height appropriate for your theme
    define('HEADER_IMAGE_HEIGHT', 195);
    define('NO_HEADER_TEXT', false );
    
    function header_style() { ?>
        <style type="text/css">
            #logo { background: url(<?php header_image(); ?>);}
        </style>
    <?php }
    function 
admin_header_style() { ?>
        <style type="text/css">
           #headimg {
                width: <?php echo HEADER_IMAGE_WIDTH?>px;
                height: <?php echo HEADER_IMAGE_HEIGHT?>px;
            }
        </style>
<?php 

get the parent category of a post
68
Put this inside the loop
------------------------------
<?php
$category 
get_the_category();
$parent get_cat_name($category[0]->category_parent);
?> 

Display the parent category
-----------------------------
<?php echo $parent?>

adding stylesheet to admin head and wp_head
69
Admin head
----------------------
<?php
    
function customstyle_css() {  ?>
            <link rel="stylesheet" type="text/css" href="<?php echo bloginfo('stylesheet_directory'?>/my_styles.css" />
    <?php 
    
}
    
add_action('admin_head''customstyle_css');
?>

wp_head
------------------------------
<?php
    
function customstyle_css() {  ?>
            <link rel="stylesheet" type="text/css" href="<?php echo bloginfo('stylesheet_directory'?>/my_styles.css" />
    <?php 
    
}
    
add_action('wp_head''customstyle_css');
?>

Cufon Font Replacement
70

Code:
-----
<script src="<?php bloginfo('template_directory')?>/font/cufon-yui.js" type="text/javascript"></script>

<script src="<?php bloginfo('template_directory')?>/font/Arial_Black_900.font.js" type="text/javascript"></script>

<script type="text/javascript">
Cufon.replace('.menu-left ul li a', { fontFamily: 'Arial Black' });
Cufon.replace('h1.title', { fontFamily: 'Arial Black' });
Cufon.replace('.home_box_1 h1 a', { fontFamily: 'Arial Black' });
});
</script>

Source:
-------
http://cufon.shoqolate.com/generate/

Display sub-page contents of a parent page
71
<div class="page_excerpts">    
            <?php
            $child_pages 
$wpdb->get_results("SELECT *    FROM $wpdb->posts WHERE post_parent = ".$post->ID."    AND post_type = 'page' ORDER BY menu_order"'OBJECT');    ?>
            <?php $count=0?>
            <?php if ( $child_pages ) : foreach ( $child_pages as $pageChild ) : setup_postdata$pageChild ); ?>
            <?php $count++ ?>
            <div class="main_exler" <?php if($count==1){?>id="first_exp"<?php }?>>

            <div class="thumbnail"><?php the_post_thumbnail(); ?></div>

            <div class="excerpt_cont">
                <h2 class="subpagetitle">
                <a href="<?php echo  get_permalink($pageChild->ID); ?>" rel="bookmark" title="<?php echo $pageChild->post_title?>">
                <?php echo $pageChild->post_title?>
                </a>
                </h2>
            
                <p>
                <?php echo substr(get_the_excerpt(),0,320).'.'?></p>
                <a class="inner_reader" href="<?php echo  get_permalink($pageChild->ID); ?>" rel="bookmark" title="Read <?php echo $pageChild->post_title?>">Read More&raquo;</a> 
                
               </div>
        <div class="clear"></div>
</div>
<?php endforeach; endif;
?>
          </div>

Display tags as list
72
<?php wp_tag_cloud('format=list'); ?>

Change background in slowmotion-using jquery
73
<script type='text/javascript'>
    $(document).ready(function(){
    $(".browse_training li").hover(
    function() {
    $(this).stop().animate({"opacity": "0.7"}, "duration: 2000").css({"background":"#2f5f99"});
    },
    function() {
    $(this).stop().animate({"opacity": "1"}, "duration: 2000");
    });
    });
</script>

CSS3 border radius for latest browsers
74
-moz-border-radius: 6px;
-khtml-border-radius: 6px;
-webkit-border-radius: 6px;
border-radius: 6px;

Remove dotted border from a button (on clicking)
75
/*for FireFox*/
    input[type="submit"]::-moz-focus-inner, input[type="button"]::-moz-focus-inner
    {   
        border : 0px;
    } 
/*for IE8 */
    input[type="submit"]:focus, input[type="button"]:focus
    {     
        outline : none; 
    }

Display child pages of current page
76
<?php $children wp_list_pages('title_li=&depth=1&child_of='.$post->ID.'&echo=0');
    if (
$children) { ?>
        <div class="sub_pages">  
              <ul> <?php echo $children?> </ul>
        </div>  
     <?php ?>

Beautiful effect to text fields on clicking
77
Put this in CSS
------------------
input[type="text"]:focus, textarea:focus{
    -moz-box-shadow:0 0 8px #f68c38;
    -webkit-box-shadow: 0 0 8px #f68c38;
    box-shadow: 0 0 8px #f68c38;
    
    border-color:#f1730c !important;
    outline:medium none;
    }

Check box using More Fields
78
<?php  $disp_post_date get_post_meta($post->ID'disp_post_date'true); // custom field value assigned to a variable?> 
<?php if(!$disp_post_date == '1'){ // display date only if not checked the 'do not display date box'?>
    <p class="meta"><small><?php the_time('l j F Y'?> </small></p>
<?php }  ?>

Force a file (here PDF) to download on click
79
Save this as "downloads.php" in site root (eg. www.mysite.com/downloads.php)
--------------------------------------------------------------------------------
<?php
function force_download($file)
{
    
//echo $file;
    
$dir      'downloads/';
    if ((isset(
$file))&&(file_exists($dir.$file))) {
      
// header("Content-Type: application/force-download");
       //header('Content-Disposition: inline; filename="' . $dir.$file . '"');
       //header("Content-Transfer-Encoding: binary");
      // header("Content-length: ".filesize($dir.$file));
       
header("Content-Type: application/pdf");
       
header('Content-Disposition: attachment; filename="' $file '"');
       
readfile("$dir$file");
    } else {
       echo 
"No file selected";
    } 
//end if
}//end function
$file stripslashes($_GET['file']);
$filename = array('book1'=>'my_ebook_name1.pdf','book2'=>'my_ebook_name2.pdf');
if(
array_key_exists($file,$filename)) {
    
force_download($filename["$file"]);
} else exit();
?>


Put ypur PDF files in a folder named "downloads"
----------------------------------------------------
my_ebook_name1.pdf
my_ebook_name2.pdf


Call using these:
----------------------
<a target="_blank" class="pdf_dwnld" href="http://www.mysite.com/downloads.php?file=book1"></a>
<a target="_blank" class="pdf_dwnld" href="http://www.mysite.com/downloads.php?file=book2"></a>

New Improved excerpt (display only 'P' tags)
80
Add this in functions.php
------------------------------
function sw_improved_excerpt($len, $terminating_string) {
        global $post;
        $text=get_the_content();
        $text=strip_tags($text);
        $text=substr($text,0,$len). $terminating_string;
        return wpautop($text, 0);
    }

Call excerpt content
-------------------------
<?php echo sw_improved_excerpt(500'....'); ?> 

Display ID of the current page
81
<?php $current_page $wp_query->get_queried_object_id();
echo 
$current_page;
?>

MD5 For Password123
82
Password
========
Password123

Md5
====
$P$BTPbNf4UAzTURxpSHjmNLBWXnKz1DM0

Improve the wp_get_archives() function
83
http://kwebble.com/blog/2007_08_15/archives_for_a_category

Contact Form7 Templatetag
84
<?php echo do_shortcode("[contact-form 1 'Advertise']"); ?>

Rounded corener in Internet Explorer versions
85
Add this .js and script to header
-------------------------------------------
http://www.sweans.org/DD_roundies_0.0.2a-min.js

<script src="<?php bloginfo('template_directory')?>/jq/DD_roundies_0.0.2a-min.js"></script>
<script>
  /* EXAMPLES */

  /* IE only */
  DD_roundies.addRule('.roundify', '10px');

  /* varying radii, IE only */
  DD_roundies.addRule('#menu li a ', '0px 0px 9px 9px');

  /* varying radii, "all" browsers
  DD_roundies.addRule('.yet_another', '5px', true); */
</script>

Facebook Share Button code for Wordpress
86
<a name="fb_share" type="button_count" share_url="<?php the_permalink(); ?>">Share</a>
<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Loader" type="text/javascript"></script>
<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>

Facebook Like Button Code for Wordpress
87
<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo urlencode(get_permalink($post->ID)); ?>&amp;layout=button_count&amp;show_faces=false&amp;width=450&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:80px; height:21px;" allowTransparency="true"> </iframe>

Display no. of posts in a category
88
add this in functions.php
-----------------------------------

function number_postpercat($idcat) {
    global $wpdb;
    $query = "SELECT count FROM $wpdb->term_taxonomy WHERE term_id = $idcat";
     $num = $wpdb->get_col($query);
    echo $num[0];
}

call by this
--------------------------
<?php number_postpercat (3); ?>

where 3 is the id of the category

WP-ecommerce products page URL (function)
89
<?php echo get_option'product_list_url' ); ?>

Display WP categories as a dropdown (with link)
90
<form action="<?php bloginfo('url'); ?>/" method="get">
<?php
$select 
wp_dropdown_categories('show_option_none=Select Category&show_count=1&orderby=name&echo=0&selected=6&show_count=0');
$select preg_replace("#<select([^>]*)>#""<select$1 onchange='return this.form.submit()'>"$select);
echo 
$select;
?>
<noscript><input type="submit" value="View" /></noscript>
</form>

POST Meta Boxed
91
<?php    
    
//SW-Custom Post Metabox Ver 1.0
    
add_action'admin_menu''my_create_post_meta_box' );
    
add_action'save_post''my_save_post_meta_box'10);

function 
my_create_post_meta_box() {
    
add_meta_box'my-meta-box''Custom Page Title''my_post_meta_box''post''normal''high' );
    
add_meta_box'my-meta-box''Custom Page Title''my_post_meta_box''page''normal''high' );
}

function 
my_post_meta_box$object$box ) { ?>
    <div id="postcustomstuff">
        <label>Please enter page title:</label>
        <input name="sw_title" id="sw_title" style="width: 97%;" value="<?php echo wp_specialcharsget_post_meta$object->ID'sw_title'true ), ); ?>" />
        
        <br /><br />
        <label>Please Page Link:</label>
        <input name="sw_page_link" style="width: 97%;" value="<?php echo wp_specialcharsget_post_meta$object->ID'sw_page_link'true ), ); ?>" />
        
        <br /><br />
        <label>Extra Content:</label><br />
        
        <textarea name="sw_extra" style="width: 98%;" rows="5"><?php echo wp_specialcharsget_post_meta$object->ID'sw_extra'true ), ); ?> </textarea>
        <input type="hidden" name="my_meta_box_nonce" value="<?php echo wp_create_nonceplugin_basename__FILE__ ) ); ?>" />
    </div>
<?php }

function 
my_save_post_meta_box$post_id$post ) {

    if ( !
wp_verify_nonce$_POST['my_meta_box_nonce'], plugin_basename__FILE__ ) ) )
        return 
$post_id;

    if ( !
current_user_can'edit_post'$post_id ) )
        return 
$post_id;

    
//Saving 1st Data
    
    
$meta_value get_post_meta$post_id'sw_title'true );
    
$new_meta_value stripslashes$_POST['sw_title'] );

    if ( 
$new_meta_value && '' == $meta_value )
        
add_post_meta$post_id'sw_title'$new_meta_valuetrue );

    elseif ( 
$new_meta_value != $meta_value )
        
update_post_meta$post_id'sw_title'$new_meta_value );

    elseif ( 
'' == $new_meta_value && $meta_value )
        
delete_post_meta$post_id'sw_title'$meta_value );
        
        
    
//Saving 2nd Data
        
    
$meta_value get_post_meta$post_id'sw_page_link'true );
    
$new_meta_value stripslashes$_POST['sw_page_link'] );

    if ( 
$new_meta_value && '' == $meta_value )
        
add_post_meta$post_id'sw_page_link'$new_meta_valuetrue );

    elseif ( 
$new_meta_value != $meta_value )
        
update_post_meta$post_id'sw_page_link'$new_meta_value );

    elseif ( 
'' == $new_meta_value && $meta_value )
        
delete_post_meta$post_id'sw_page_link'$meta_value );    
        
    
//End 2nd Data Saving
    
    
$meta_value get_post_meta$post_id'sw_extra'true );
    
$new_meta_value stripslashes$_POST['sw_extra'] );

    if ( 
$new_meta_value && '' == $meta_value )
        
add_post_meta$post_id'sw_extra'$new_meta_valuetrue );

    elseif ( 
$new_meta_value != $meta_value )
        
update_post_meta$post_id'sw_extra'$new_meta_value );

    elseif ( 
'' == $new_meta_value && $meta_value )
        
delete_post_meta$post_id'sw_extra'$meta_value );    
}
?>

Display the content of sub pages (of the current page)
92
<?php 
    $child_pages 
$wpdb->get_results("SELECT *    FROM $wpdb->posts WHERE post_parent = ".$post->ID."    AND post_type = 'page' ORDER BY menu_order"'OBJECT');    
    if ( 
$child_pages ) : foreach ( $child_pages as $pageChild ) : setup_postdata$pageChild ); 
?>
    <li><a href="<?php echo get_permalink($pageChild->ID); ?>"><?php echo $pageChild->post_title?></a></li>
<?php endforeach; endif;?>

parameters for query_posts();
93
    * attachment
    * attachment_id
    * author
    * author_name
    * cat
    * category__and
    * category__in
    * category__not_in
    * category_name
    * comments_popup
    * day
    * error
    * feed
    * hour
    * m
    * minute
    * monthnum
    * name
    * order
    * orderby
    * p
    * page_id
    * page
    * paged
    * pagename
    * post__in
    * post__not_in
    * post_status
    * post_type
    * preview
    * robots
    * s
    * sentence
    * second
    * static
    * subpost
    * subpost_id
    * tag__and
    * tag__in
    * tag__not_in
    * tag_id
    * tag_slug__and
    * tag_slug__in
    * tag
    * taxonomy - (pre 3.1)
    * tb
    * term - (pre 3.1)
    * w
    * withcomments
    * withoutcomments
    *

      year

      Pre WP 3.1
    * meta_key
    *

      meta_value

      Since WP 3.1
    * fields
    * meta_query
    * tax_query

Setting thank_you page for Contact form 7
94
add this to the "additional settings" section:

on_sent_ok: "location.replace('http://www.YOURSITE.com');"

Get all the wordpress category ID's except some
95
$category_ids = get_all_category_ids();
        $cat='';
        foreach($category_ids as $cat_id) {
            if( ($cat_id!=7) && ($cat_id!=4 ) ) {
                if(!$cat ) {
                    $cat=$cat_id;
                } else {
                    $cat.= "," . $cat_id;
                }
            }
        }

Display Wordpress categories not as a list (display as links)
96
// user-defined functions start in the next blank line:
add_filter('wp_list_categories', 'myCatNoBrk', 10, 1);
function myCatNoBrk($OrgCat) {
   $CatNoBrk = preg_replace('/<br \/>/',',',$OrgCat);
   return $CatNoBrk;
}

Search field clear text
97
<input type="text" class="text" value="Site Search..." name="s" id="s" onfocus="if (this.value == 'Site Search...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Site Search...';}"/>

Display subpages of the current page
98
<?php
global $wp_query;
if( empty(
$wp_query->post->post_parent) ) {
$parent $wp_query->post->ID;
} else {
$parent $wp_query->post->post_parent;
}
wp_list_pages("title_li=&child_of=$parent");
?> 

JavaScript pop-up window on button click
99
In header
---------------------
<script language="JavaScript">
    function popUp(URL) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=1440,height=900');");
    }
</script>

Call it anywhere
-------------------------------
<form>
<input type=button value="Open the Popup Window" onClick="javascript:popUp('http://google.com')">
</form>

Rotate on page refresh
100
<div id="refresh_link">
<?php
 $var_link_counter 
rand(1,3);

 if(
$var_link_counter == 1){
    echo 
'<a href="http://192.168.1.47/dorothycottoninstitute/support/volunteer/">VOLUNTEER TODAY<img src="http://192.168.1.47/dorothycottoninstitute/wp-content/uploads/2011/06/arrow.jpg" alt="" /></a>';
 } else if(
$var_link_counter == 2){
      echo 
'<a href="http://192.168.1.47/dorothycottoninstitute/learn/media-center/">VIEW MEDIA<img src="http://192.168.1.47/dorothycottoninstitute/wp-content/uploads/2011/06/arrow.jpg" alt="" /></a>' ;
 } else {
      echo 
'<a href="http://192.168.1.47/dorothycottoninstitute/support/donate/">DONATE <img src="http://192.168.1.47/dorothycottoninstitute/wp-content/uploads/2011/06/arrow.jpg" alt="" /></a>' ;
 }

?>
</div>

Restrict Admin Menu Items Based on Username
101
function remove_menus()
{
    global $menu;
    global $current_user;
    get_currentuserinfo();
 
    if($current_user->user_login == 'clients-username')
    {
        $restricted = array(__('Posts'),
                            __('Media'),
                            __('Links'),
                            __('Pages'),
                            __('Comments'),
                            __('Appearance'),
                            __('Plugins'),
                            __('Users'),
                            __('Tools'),
                            __('Settings')
        );
        end ($menu);
        while (prev($menu)){
            $value = explode(' ',$menu[key($menu)][0]);
            if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
        }// end while
 
    }// end if
}
add_action('admin_menu', 'remove_menus');

Hide the WordPress Upgrade Message
102
add_action('admin_menu','wphidenag');
function wphidenag() {
remove_action( 'admin_notices', 'update_nag', 3 );
}

Changing the WP Login Logo
103
// login page logo
function custom_login_logo() {
    echo '<style type="text/css">h1 a { background: url('.get_bloginfo('template_directory').'/companylogo.png) 50% 50% no-repeat !important; }</style>';
}
add_action('login_head', 'custom_login_logo');

Enable multi site in Wordpress 3.x
104
define('WP_ALLOW_MULTISITE', true);

Edit the content of a web page in browser (for testing)
105
Enter the following in the address bar and hit enter:

javascript: document.body.contentEditable= "true"; document.designMode= "on"; void 0

Display errors publically (to rectify)
106
Add this code in wp-config.php just before /** Sets up WordPress vars and included files. */
/*Start-For Debugging Purpose*/
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('display_startup_errors', true);
/*End- For Debugging Purpose*/

Increase PHP memory limit
107
Add this in wp-config.php

@ini_set('memory_limit', '256M');

Search Box with Category filter
108
<form role="search" method="get" id="searchform" action="<?php bloginfo('siteurl'); ?>/">
<div>

<label class="screen-reader-text" for="s">Search for:</label>
<input type="text" value="" name="s" id="s" />in <?php wp_dropdown_categories'show_option_all=All Categories' ); ?> 
<input type="submit" id="searchsubmit" value="Search" />

</div>
</form>

Disappear a div on clicking x
109
<a href="#" onclick="jQuery('.close_window').hide('slow'); return false;">x</a>
<div class="close_window">this text will disappear on clicking "x"></div>

Setting Cookie and checking
110
Add this before HTML tag
--------------------------------------------
<?php 
    $expire
=time()+60*60*24*30;
    
setcookie("user""sweans"$expire);
?>

Then use this in code:
-----------------------------------------
<?php
    
if (isset($_COOKIE["user"]))
      echo 
"Welcome " $_COOKIE["user"] . "!<br />";
    else
      echo 
"Welcome guest!<br />";
?>

List pages include tree function
111
Add this in functions.php
--------------------------------------
<?php
 
function js_list_pages_include_tree($args){
$defaults = array(
'depth' => 0'show_date' => '',
'date_format' => get_option('date_format'),
'child_of' => 0'exclude' => '',
'title_li' => __('Pages'), 'echo' => 1,
'authors' => '''sort_column' => 'menu_order, post_title',
'link_before' => '''link_after' => '',
'include_tree' => 0
);
 
$r wp_parse_args$args$defaults );
 
// Print the parent page
$pages get_pages('title_li=&include='.$r['include_tree'].'&depth=0');
 
// Print the children
foreach ($pages as $pagg){
echo 
'<li><a href="'.get_page_link($pagg->ID).'">'$pagg->post_title.'</a>';
echo 
"<ul>";
wp_list_pages('title_li=&child_of='.$r['include_tree'].'&depth='.($r['depth']-1));
echo 
"</ul>";
echo 
'</li>';
}
 
}
 
?>

Calling
----------------------------------
<?php js_list_pages_include_tree('include_tree=10'); ?>

Hide an element on clicking-using jQuery
112
<a id="clickme" href="#">Click me to hide</a>
<p id="hider">Here is another paragraph</p>
<script>
   $("#clickme").click(function (event) {
      event.preventDefault(); //not to display # in address bar
      $("#hider").hide("slow");
    }); 
</script>

Display content using getElementById() - JavaScript
113
<script>
function displayit() {
    document.getElementById('disp_div').innerHTML = "Hiii, I came as new text!";
}
</script>
<button onClick="displayit()">Display it!</button>
<div id="disp_div">Here ill come the new text!</div>

Getting the url of the post thumbnail
114
 <?php $url wp_get_attachment_urlget_post_thumbnail_id($post->ID) );?>

Display the terms of a post
115
<ul>
<?php echo get_the_term_list$post->ID'taxonomy_name''<li/> ''<li>''' ); ?>
</ul>

Increase upload limit in Wamp Server
116
Open C:\wamp\bin\apache\apache2.2.8\bin\php.ini

Find:
post_max_size = 8M
upload_max_filesize = 2M
max_execution_time = 30
max_input_time = 60
memory_limit = 8M

Change to:
post_max_size = 750M
upload_max_filesize = 750M
max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M

Then restart wamp to take effect

WordPress Database Schema
117
The following link shows the image of the data base schema of wordpress
http://www.jayminkapish.com/wp-content/uploads/2009/03/wp_2.7.png

Generate Facebook like box code for fan page
118
http://developers.facebook.com/docs/reference/plugins/like-box/

To Validate Javascript
119
<script type="text/javascript">
//<![CDATA[

// rest of your javascript goes here

//]]>
</script>

Display random number
120
<?php echo(rand(1,3)); ?>

Fade on hover
121
<script type="text/javascript">
$("document").ready(function(){
$("#mover").hover(
    function(){ 
        $(this).stop().animate({"opacity": "0.8"});
        },
    function(){
        $(this).stop().animate({"opacity": "1"});
});
});
</script>

Display comment form with a post queried somewhere
122
<?php
$withcomments 
true;
comments_template();
?>

Change capabilities of a default user role
123
$_the_roles = new WP_Roles();
$_the_roles->add_cap('author','edit_pages');
$_the_roles->remove_cap('author','manage_options');

Adding WYSIWYG editor to theme options
124
Add this above to the theme options code
-----------------------------------------------------------------
add_action("admin_head","myplugin_load_tiny_mce");
function myplugin_load_tiny_mce() {
wp_tiny_mce( true ); // true gives you a stripped down version of the editor
}

Then add this class "theEditor" to the input area box
---------------------------------------------------------------------------
Eg: <textarea rows="5" class="theEditor" style="width:400px;" cols="77" name="sw_banner_content"><?php echo get_option('sw_banner_content'); ?></textarea>

Customizing Facebook fan widget
125
Get the Facebook fan widget code code:
-------------------------------------------
<div id="fb-root"></div>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>
<script type="text/javascript">FB.init("fd161b28d6338cb852d8ed87878f67c3");</script>
<fb:fan profile_id="148736628491372" connections="10" width="335" height="300" css="<?php bloginfo('stylesheet_url'); ?>?1></fb:fan> 
<script src="js/fbvalidate.js" type="text/javascript"></script>


<?php bloginfo('stylesheet_url'); ?>?1 (as we make edit in style sheet make ?1 as ?2)


In CSS paste this code: (You can edit as your wish)
--------------------------------------------------

.fan_box .full_widget {
    background: none; border: none;
}
.fan_box .connections_grid .grid_item {
    padding: 0 8px 10px 8px;
}
    .fan_box .connections_grid .grid_item a img {
        box-shadow: 0px 0px 10px #333; -moz-box-shadow: 0px 0px 10px #333; -webkit-box-shadow: 0px 0px 10px #333;
    }
        .fan_box .connections_grid .grid_item a:hover img {
            box-shadow: 0px 3px 10px #333; -moz-box-shadow: 0px 3px 10px #333; -webkit-box-shadow: 0px 3px 10px #333;
        }
.fan_box .full_widget .connect_top {
    background: url(http://line25.com/wp-content/uploads/2010/facebook/demo/images/blue.png);
    border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px;
}
.fan_box .connections .connections_grid {
    padding-top:16px;
}
.fan_box .connections {
    border-top: none;
    padding:15px 0 0;
    color: #ccc;
    font: italic 21px Georgia;
    text-align: center;
    text-shadow: 0px 1px 4px #000;
}
    .fan_box .connections span.total {
        color: #fff;
    }

.fan_box .connections_grid .grid_item .name {
    color: #ccc;
    font-size: 11px;
}
.fan_box .profileimage {
    margin: 0;
}

How to remove menus in WordPress dashboard
126
function remove_menus () {
global $menu;
    $restricted = array(__('Dashboard'), __('Posts'), __('Media'), __('Links'), __('Pages'), __('Appearance'), __('Tools'), __('Users'), __('Settings'), __('Comments'), __('Plugins'));
    end ($menu);
    while (prev($menu)){
        $value = explode(' ',$menu[key($menu)][0]);
        if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
    }
}
add_action('admin_menu', 'remove_menus');

Exclude featured image from attached images
127
<?php 
// Function definition
function get_images($size 'thumbnail') {
    
$thumb_ID get_post_thumbnail_id$post->ID ); // For excluding the featured image
    
global $post;
    return 
get_children( array(
        
'post_parent' => get_the_ID(), 
        
'post_status' => 'inherit'
        
'post_type' => 'attachment'
        
'post_mime_type' => 'image'
        
'order' => 'ASC'
        
'orderby' => 'menu_order ID',
        
'exclude' => $thumb_ID// excluded featured image here
    
));


// Displaying the contents
$photos get_images('full');
if (
$photos){
    foreach (
$photos as $photo){
        echo(
'<img alt="'.$photo->post_title.'" src="'.wp_get_attachment_url($photo->ID).'" />' "\n");
     }
 } 
// fired by aboobacker.com
?>

Favicon Implementation
128
Generate Favicon from http://tools.dynamicdrive.com/favicon/
<link rel="shortcut icon" type="image/x-icon" href="<?php bloginfo('template_directory')?>/favicon.ico" />

To Get Recent Comments of a specific Post/Page
129
<div class="recent_main">
<?php $comments get_comments('post_id=30&number=1');
    foreach(
$comments as $comment) : ?>
        <div class="recent_entry">
            <?php echo get_comment_text(); ?>
            <?php echo($comment->comment_author); ?>
        </div> 
    <?php endforeach;?>
</div>

Function REF
-------------------
http://codex.wordpress.org/Function_Reference/get_comments

Allow Shortcode on custom field
130
Just put this code into whatever page you are displaying the results of the shortcode, and change the 'your_custom_field_here' to the name of your custom field. 

<?php echo apply_filters('the_content'get_post_meta($post->ID'your_custom_field_here'true)); ?>

Creating Your Own Page Templates
131
<?php
/*
Template Name: Page Name
*/
?>

JQuery Ajax snippet
132
<script src="http://code.jquery.com/jquery-1.6.4.js"></script>
<script>
$(function(){
    $("#your_form_id").submit(function(e){

       e.preventDefault();

        dataString = $("#your_form_id").serialize();

        $.ajax({
        type: "POST",
        url: "process_form.php",
        data: dataString,
        dataType: "json",
        success: function(data) {

        }

        });          
    });
});
</script>

Paginated Page Template
133
<?php
        
global $paged;
        if(!
$paged) {
            
query_posts('showposts');
        }else {
            
query_posts('showposts&paged=' $paged);
        }
?> 
<div class="main_entry">
        <?php while (have_posts()) : the_post(); ?>
        <div class="main_entry_item">
        <a href="<?php echo get_permalink() ?>">
        <?php the_title(); ?></a>
        <?php the_content(); ?>
        </div>
        <div class="navigation">
            <div class="alignleft"><?php next_posts_link('&laquo; Older Entries'?></div>
            <div class="alignright"><?php previous_posts_link('Newer Entries &raquo;'?></div>
        </div>
        <?php endwhile; ?>
</div>
<?php wp_reset_query();?> 

Custom field specific Loop
134
 <?php 
    $prdcat_id 
get_post_meta($post->ID'prdcat_id'true);
    
// assign the variable as current category
    
$categoryvariable $prdcat_id;

    
// concatenate the query
    
$args 'cat=' $categoryvariable '&showposts';
    
$args_paged 'paged=' $paged '&cat=' $categoryvariable '&showposts';
    
    
?>
    
        <?php
        
global $paged;
        if(!
$paged) {
            
query_posts$args );
        }else {
            
query_posts$args_paged );
        }
?>  

WP-Ecommerce template codes
135
Display Shopping Cart:< ?php echo nzshpcrt_shopping_basket(); ?>
List Categories: < ?php show_cats_brands(); ?>
Buy Now: < ?php echo wpsc_buy_now_button(1); ?>
Add to Cart: < ?php echo wpsc_add_to_cart_button(1); ?>
Display Latest Products: <?php nzshpcrt_latest_product(); ?>
Display SKU: <?php echo wpsc_product_sku(wpsc_the_product_id());  ?>

include links in wp_list_pages() within span
136
<?php
                        $pagetest 
wp_list_pages'echo=0&title_li=' );
                        
$pagetest str_replace'><a href' '><span><a href' $pagetest );
                        
$pagetest str_replace'</a></li>' '</a></span></li>' $pagetest );
                        echo( 
$pagetest );
?>

Remove menus from WP admin panel
137
function remove_menus () {
global $menu;
    $restricted = array(
            __('Dashboard'), 
           // __('Posts'),
            __('Media'), 
            __('Links'), 
            __('Pages'), 
           // __('Appearance'), 
            __('Tools'), __('Users'), 
            __('Settings'), 
            __('Comments'), 
            __('Plugins'));
    end ($menu);
    while (prev($menu)){
        $value = explode(' ',$menu[key($menu)][0]);
        if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
    }
}
add_action('admin_menu', 'remove_menus');

Change "Posts" to something else in admin panel
138
function change_post_to_article( $translated ) {
   $translated = str_ireplace(  'Post',  'Blog Post',  $translated );
   return $translated;
}
add_filter(  'gettext',  'change_post_to_article'  );

Check whether a page has parent page (or page is child page of another page)
139
In functions.php
------------------------------
function is_child($pageID) { 
    global $post; 
    if( is_page() && ($post->post_parent==$pageID) ) {
               return true;
    } else { 
               return false; 
    }
}

Checking:
---------------------------------
<?php
if(is_child(123)) {
echo 
"This is a child page of 'The Parent Page Title'.";
}
?>

Display sub pages of current page
140
<?php 
$pages 
get_pages(array('child_of' => $post->ID'post_type' => 'page''sort_column' => 'menu_order'));
    foreach (
$pages as $pagg) {
        
$option '<a href="' get_page_link($pagg->ID) . '">';
        
$option .= $pagg->post_title;
        
$option .= '</a>';
        echo 
$option;
    }
?>

Check whether the post is belongs to a post type
141
<?php
// function to check whether the post is belongs to a post type
function is_post_type($type) {
    global 
$wp_query;
    if(
$type == get_post_type($wp_query->post->ID)) return true;
    return 
false;
}
?>

-----------------------------
<?php is_post_type('our_post_type') { echo " it's from that post type"; }  ?>

Includea in the wp_list_pages (inside 'a' tag)
142
<?php
    $pages 
wp_list_pages('echo=0&title_li=');
    
$pages str_replace('">''"><span>'$pages);
    
$pages str_replace('<span><a''<a'$pages);
    
$pages str_replace('</a>''</span></a>'$pages);
    echo 
$pages;
?>

Fetch data from WP database table
143
<?php
global $wpdb;
$table $wpdb->prefix 'table_name';
$querried $wpdb->get_results"SELECT * FROM $table WHERE id = 1");
echo 
$querried[0]->value
?>

CSS Reset
144
html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, code,
del, dfn, em, img, q, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td { margin: 0px; padding: 0px; border: 0px; font-weight: inherit; font-style: inherit; font-size: 100%; font-family: inherit; vertical-align: baseline; }

/* Removes dotted line when focus */
:focus { outline: none; }

/* Tables still need 'cellspacing="0"' in the markup. */
table { border-collapse: separate; border-spacing: 0px; }
caption, th, td { text-align: left; font-weight: normal; }
table, td, th { vertical-align: middle; }

/* Remove possible quote marks (") from <q>, <blockquote>. */
blockquote:before, blockquote:after, q:before, q:after { content: ""; }
blockquote, q { quotes: "" ""; }

/* Remove annoying border on linked images. */
a img { border: none; }

/* Clearing floats without extra markup
   Based on How To Clear Floats Without Structural Markup by PiE
   [http://www.positioniseverything.net/easyclearing.html] */
.clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
.clearfix { display: block; }

/* Regular clearing, just in case! */
.clear { clear: both; }

Query a specific Taxonomies With More Taxonomies Plugin
145
<?php
query_posts
(array( 'post_type' => 'portfolio''portfoliocat' => 'images''posts_per_page' => 10000 ) );      
?> 

----------------
portfoliocat is the name of query variable defined at More Taxonomies Plugin plugin under advanced settings

Life Span of a Post (Time Ago)
146
<?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'?>

URL of Featured custom Image
147
<?php $url wp_get_attachment_image_srcget_post_thumbnail_id$post->ID ), 'welcome_image' ); ?>

<div  style="background-image:url(<?php echo $url[0]; ?>)">

</div>

Folde sideMenu With plugin
148
Plugin:
======
Folder Pages

HTML
======
 <div id="sidebar_subpage">
        <ul>
           
                <?php wswwpx_fold_page_list ('depth=3&sort_column=menu_order&title_li='); ?>
            
        </ul>
    </div>


CSS
====

/*------SIDEMENU CSS-----------*/
#sidebar_subpage {
    margin-top: 10px;
}
#sidebar_subpage ul li a {
    color: #CCCCCC;
    font-family: "Lucida Sans", Arial;
    font-size: 16px;
    text-decoration: none;
}
#sidebar_subpage ul li li a {
    font-size: 14px;
    color: #CCCCCC !important;
}
#sidebar_subpage ul ul .current_page_item a {
    color: #FF3333 !important;
}
#sidebar_subpage ul ul ul .page_item a { 
    color: #CCCCCC !important;
}
#sidebar_subpage ul current_page_ancestor a {
    color: #FF3333 !important;
}
#sidebar_subpage ul li ul {
    margin-bottom: 3px;
    margin-top: 3px;
}
#sidebar_subpage ul li li li a {
    font-size: 12px;
}
.current_page_item a{
    color: #FF3333 !important;
}
.current_page_parent a{
    color: #FF3333;

.current_page_ancestor a{
    color: #FF3333 !important;
}
.current_page_ancestor .current_page_ancestor a{
    color: #FF3333 !important;
}

#sidebar_subpage ul .current_page_ancestor ul .current_page_ancestor a {
    color: #FF3333 !important;
}
#sidebar_subpage ul .current_page_ancestor ul .current_page_ancestor ul .page_item a {
    color: #CCCCCC !important;
}
#sidebar_subpage ul .current_page_ancestor ul .current_page_ancestor ul .page_item a {
    color: #CCCCCC !important;
}

#sidebar_subpage ul .current_page_ancestor ul .current_page_ancestor ul .current_page_item a {
    color: #FF3333 !important;
}
/*------SIDEMENU CSS-----------*/

Content Of a Specific Page
149
 <?php query_posts('page_id=21') ; ?> 
    <?php if (have_posts()) : ?> 
     <?php while (have_posts()) : the_post(); ?>  
        <div class="post" id="post-<?php the_ID(); ?>">  
       <?php echo get_the_content(); ?> 
        </div> 
    
    <?php endwhile; ?>  
    <?php wp_reset_query();?>  
    <?php else : ?>  
    <div class="title">Not Found</div> 
    <p>Sorry, but you are looking for something that isn't here.</p>  
    <?php endif; ?> 

Menu with Default Frame work Theme
150
DEFINE:
------------
register_nav_menus( array('main_nav' => __( 'Primary Navigation', 'sw theme'))); 

USAGE:
------------
<div id="menu">        
    <?php wp_nav_menu( array( 'container_class' => 'menu-header''theme_location' => 'main_nav','container' => false,'menu_id' => 'dropmenu' ) ); ?>    
</div>


Dynamic height to a DIV using Jquery
151
jQuery(document).ready(function() {
var x = $(".contentmainpage").height();
$(".leftsidebar").css({height: x });

});

Next / Previous post links (URL's only)
152
Add in functions.php
---------------------------------------------
<?php
    
function next_post_url($in_same_cat=false$excluded_categories ''$display=true) {
        
$post get_next_post($in_same_cat$excluded_categories);
        if (
$post) {
            
$url get_permalink($post->ID);
            if(
$display) {
                echo 
$url;
            }
            return 
$url;
        }
    }
    
    function 
previous_post_url($in_same_cat=false$excluded_categories ''$display=true) {
        
$post get_previous_post($in_same_cat$excluded_categories);
        if (
$post) {
            
$url get_permalink($post->ID);
            if(
$display) {
                echo 
$url;
            }
            return 
$url;
        }
    }
?>

Call them
----------------------------------
<?php previous_post_url(display); ?>
<?php next_post_url
(display); ?>

Public Tweet URI
153
http://twitter.com/home?status=<?php the_permalink();?>

Read more tag in query posts
154
<?php
global $more;    // Declare global $more (before the loop).
$more 0;       // Set (inside the loop) to display content above the more tag.
the_content("More...");
?>

WordPress asks ftp password on any upgrade or install
155
To avoid wordpress asking for ftp un and pw for any upgrade do the following :

open   wp-config.php and insert the following

define('FTP_USER', 'username');
define('FTP_PASS', 'password');
define('FTP_HOST', 'ftp.example.org:21');

Check whether a page is child/grand child of another page
156
function is_tree($pid) {      // $pid = The ID of the page we're looking for pages underneath
    global $post;         // load details about this page
    $anc = get_post_ancestors( $post->ID );
    foreach($anc as $ancestor) {
        if(is_page() && $ancestor == $pid) {
            return true;
        }
    }
    if(is_page()&&(is_page($pid)))
               return true;   // we're at the page or at a sub page
    else
               return false;  // we're elsewhere
};

Display the parent category posts; not the sub page posts
157
<?php
global $paged;
                    
$cat 1;
                    if(!
$paged) {
                        
query_posts(array('category__in' => array($cat)));
                    }else {
                        
query_posts(array('category__in' => array($cat),'paged' => $paged));
                    }
?>

Check if a post is under a category of child category (for special templating)
158
Add in functions.php
---------------------------------
<?php
function is_desc_cat($cats$_post null) {
  foreach ((array)
$cats as $cat) {
    if (
in_category($cat$_post)) {
      return 
true;
    } else {
      if (!
is_int($cat)) $cat get_cat_ID($cat);
      
$descendants get_term_children($cat'category');
      if (
$descendants && in_category($descendants$_post)) return true;
    }
  }
return 
false;
}
?>

Check using:
------------------------
<?php if (is_desc_cat(1)) ?>

.htaccess redirect for mobile browsers
159
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_USER_AGENT} android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge\ |maemo|midp|mmp|opera\ m(ob|in)i|palm(\ os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows\ (ce|phone)|xda|xiino [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a\ wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r\ |s\ )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1\ u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp(\ i|ip)|hs\-c|ht(c(\-|\ |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac(\ |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt(\ |\/)|klon|kpt\ |kwc\-|kyo(c|k)|le(no|xi)|lg(\ g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-|\ |o|v)|zz)|mt(50|p1|v\ )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v\ )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-|\ )|webc|whit|wi(g\ |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-) [NC]
RewriteRule ^$ http://m.website.com [R,L]

How to Execute PHP in WordPress Text Widgets without any Plugins
160
Add to functions.php
--------------------------------
add_filter('widget_text','execute_php',100);
function execute_php($html){
     if(strpos($html,"<"."?php")!==false){
          ob_start();
          eval("?".">".$html);
          $html=ob_get_contents();
          ob_end_clean();
     }
     return $html;
}

Adding Class to first letter of a div
161
<script type='text/javascript'>
    $(document).ready(function() {
    
        $("#price_new .amount").each(function() {
        var text = $(this).html();
        var first = $('<span>'+text.charAt(0)+'</span>').addClass('DxStyle');
        $(this).html(text.substring(1)).prepend(first);
        });
    
    });
    </script>

Excerpt With word Limit
162
Function:
------------------------------
function string_limit_words($string, $word_limit)
{
  $words = explode(' ', $string, ($word_limit + 1));
  if(count($words) > $word_limit)
  array_pop($words);
  return implode(' ', $words);
}

Usage:
------------------------------
<?php
              $excerpt 
get_the_excerpt();
              echo 
string_limit_words($excerpt,20);
?>

Pass a value to automatically select from multiple selection menu in a page
163
<script>
    $(document).ready(function(){
        var valArr = ['Word to be selected'],
        i = 0, size = valArr.length,
        $options = $('.select_class option');
        for(i; i < size; i++){
            $options.filter('[value="'+valArr[i]+'"]').prop('selected', true);
        }
    });
    </script>

Adding new custom post type with taxonomy
164
function my_post_type_portfolio() {
    register_post_type( 'portfolio',
                array( 
                'label' => __('Portfolio'), 
                'singular_label' => __('Porfolio Item', 'theme1662'),
                '_builtin' => false,
                'public' => true, 
                'show_ui' => true,
                'show_in_nav_menus' => true,
                'hierarchical' => true,
                'capability_type' => 'page',
                'menu_icon' => get_template_directory_uri() . '/includes/images/icon_portfolio.png',
                'rewrite' => array(
                    'slug' => 'portfolio-view',
                    'with_front' => FALSE,
                ),
                'supports' => array(
                        'title',
                        'editor',
                        'thumbnail',
                        'excerpt',
                        'custom-fields',
                        'comments')
                    ) 
                );
    register_taxonomy('portfolio_category', 'portfolio', array('hierarchical' => true, 'label' => 'Portfolio Categories', 'singular_name' => 'Category', "rewrite" => true, "query_var" => true));
}

add_action('init', 'my_post_type_portfolio');

PHPBB to WORDPRESS Content
165
<?php
$connection 
mysql_connect(localhost,"your_login","your password") or die("Service temporairly unavailable");
$db mysql_select_db("your_db_name",$connection) or die("Service temporairly unavailable");
$sql "select * from phpbb_topics order by topic_last_post_time desc limit 0,10";
$result mysql_query($sql) or die("Service temporairly unavailable");
for(
$x=1;$x<=10;$x++){
    
$row mysql_fetch_array($result);
    echo 
"<a href = \"http://www.yourforumdomain.com/viewtopic.php?f=$row[forum_id]&t=$row[topic_id]\" target = \"_blank\">$row[topic_title]</a><br>";
}
?>

Display current template
166
<?php global $template; echo basename($template); ?>

Ajax with Query and wordpress
167
HEADER
==========
<script type='text/javascript'>
$(document).ready(function(){
    $.ajaxSetup({cache:false});
    $(".SideClick").click(function(){
        $(".SideClick").removeClass("PrdNow");
        $(this).addClass("PrdNow");    
        var post_id = $(this).attr("rel");
        $("#single-home-container").load("<?php bloginfo('template_directory')?>/prd_ajax.php",{id:post_id}, function() {
        $(".mainPRDCurrent").hide('slow');

});    
    return false;
    });
});
</script>

LINK:
========
 <li><a rel="<?php the_ID(); ?>" id="<?php the_ID(); ?>" class="SideClick"><?php the_title(); ?></a></li>  


AJAX FILE
===========
<?php
define
('WP_USE_THEMES'false);  
require_once(
'../../../wp-load.php'); 
?>

<?php $product_ID $_POST["id"]; ?>

Display all the tags as checkboxes
168
<?php
$tags 
get_tags();
$html '<form action="">';
foreach (
$tags as $tag){
    
$html .= '<input type="checkbox" name="'.$tag->name.'" value="'.$tag->name.'"> '.$tag->name.' ';
}
$html .= '</form>';
echo 
$html;
?>

Get the current category details (in category.php)
169
<?php
if (is_category( )) {
  
$cat get_query_var('cat');
  
$yourcat get_category ($cat);
  echo 
'the slug is '$yourcat->slug;
 }
?>

Get the database host
170
$_ENV{DATABASE_SERVER}

Flush rewrite rule after register post type
171
flush_rewrite_rules();

Remove blank lines in code using dreamweaver
172
1.    Click CTRL + F
2.    Select â€œCurrent documentâ€? in â€œFind inâ€? (You can also select the folder if you have multiple files)
3.    Search in â€œSource codeâ€?
4.    Tick â€œUse regular expressionâ€?
5.    Type â€œ[\r\n]{2,}â€? (without quotes) in â€œFindâ€?
6.    Type â€œ\nâ€? (without quotes) in â€œReplaceâ€?
7.    Press â€œReplace Allâ€?

Upload Box on Theme Option
173
Function
=========
    
    // create custom plugin settings menu
add_action('admin_menu', 'sw_create_menu');

function sw_create_menu() {

    //create new top-level menu
    add_menu_page('Theme Options', 'Theme Options', 'add_users', 'cms_settings', 'sw_settings_page', get_bloginfo("template_url") .'/images/icon.png',32);
    
    //call register settings function
    add_action( 'admin_init', 'register_mysettings' );
}


function register_mysettings() {
    //register our settings
    register_setting( 'sw-settings-group', 'dx_site_logo' );
    
}

function sw_settings_page() {
    
    
?>
<div class="wrap">
<h2> CMS Options</h2>

<form method="post" action="options.php">
    <?php settings_fields'sw-settings-group' ); ?>
    <table class="form-table">
      
      
      
        
        
        <tr valign="top">
        <th scope="row">Upload Logo: </th>
        <td><img src="<?php echo get_option('dx_site_logo'); ?>" width="250px" height="75px" /> <br />
        
        <label for="upload_image">
        <input id="logo_upload_image" type="text" size="85" name="dx_site_logo" value="" />
        <input id="logo_upload_image_button" type="button" class="button" value="Upload Image" />
        <br />Enter an URL or upload an image for the logo. <br />
        <small> Please use image with Width:250Px, Height:75px
        </label></td>
        </tr>
       
        
    </table>
    
    <p class="submit">
    <input type="submit" class="button-primary" value="<?php _e('Save Changes'?>" />
    </p>

</form>
</div>
<?php }

function 
my_admin_scripts() {
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_register_script('my-upload'WP_CONTENT_URL.'/themes/dxtheme/my-script.js', array('jquery','media-upload','thickbox'));
wp_enqueue_script('my-upload');
}

function 
my_admin_styles() {
wp_enqueue_style('thickbox');
}

if (isset(
$_GET['page']) && $_GET['page'] == 'cms_settings') {
add_action('admin_print_scripts''my_admin_scripts');
add_action('admin_print_styles''my_admin_styles');
}

/
my-script.js
==========
jQuery(document).ready(function() {

jQuery('#logo_upload_image_button').click(function() {
 
formfield jQuery('#logo_upload_image').attr('name');
 
tb_show('''media-upload.php?type=image&amp;TB_iframe=true');
 return 
false;
});

window.send_to_editor = function(html) {
 
imgurl jQuery('img',html).attr('src');
 
jQuery('#logo_upload_image').val(imgurl);
 
tb_remove();
}

});

Link WP login/register logo to home page
174
Add in functions.php
----------------------------------

add_filter( 'login_headerurl', 'custom_loginlogo_url' );
function custom_loginlogo_url($url) {
    return site_url();
}

Sidebar menu with level opener
175
// New custom menu for sidebar
function ab_custom_submenu($menuId) {
 global $post;
 $menu_items = wp_get_nav_menu_items('Sidebar Menu');
 $current_menu_id = $menuId;
 // get current top level menu item id
 foreach ( $menu_items as $item ) {
  if ( $item->object_id == $menuId ) {
   // if it's a top level page, set the current id as this page. if it's a subpage, set the current id as the parent
   $current_menu_id = ( $item->menu_item_parent ) ? $item->menu_item_parent : $item->ID;
   break;
  }
 }
 // display the submenu
 foreach ( $menu_items as $item ) {
  if ( $item->menu_item_parent == $current_menu_id ) {
   $class = ( $item->object_id == $menuId ) ? "class='current_page_item'" : "";
   echo "<li><a href='{$item->url}'>{$item->title}</a></li>";
  }
 }
}

PHP CLASS Concept
176
class TouchClass {   
    public function add_users($user_name, $user_email, $user_pass, $user_role, $user_designation,$user_phone, $user_image){       
            $result = mysql_query("INSERT INTO users(
            user_name, user_email, user_pass, user_role, user_designation, user_phone, user_image) 
            values ('$user_name', '$user_email','$user_pass','$user_role','$user_designation','$user_phone', '$user_image')")
            or die(mysql_error());
            return $result;
       
    }

public function list_all_bids ($sort_type, $sort_valuse){
        
      
        $rs = mysql_query("select * from  tb_bidding ORDER BY $sort_type $sort_valuse");
       
        $i = 0;
        while ($row = mysql_fetch_assoc($rs)) {
            
        $result[$i]['bid_id'] = $row['bid_id'];
        $result[$i]['bid_name'] = $row['bid_name'];
        $result[$i]['bid_status'] = $row['bid_status'];
        $result[$i]['bid_price'] = $row['bid_price'];
        $result[$i]['bid_user'] = $row['bid_user'];
        $result[$i]['bid_time'] = $row['bid_time'];
        $result[$i]['bid_source'] = $row['bid_source'];
        $i++;
        }
        return $result;
        }

}

---------

 <?php
   
    
    
if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
       
   
            
        
    
$adduser $touchObj->add_users(
            
$_POST['username'],
            
$_POST['useremail'], 
            
$_POST['userpass'], 
            
$_POST['userrole'],
            
$_POST['userdesignation'],
            
$_POST['user_phone'],
            
$_POST['user_image']
            );
    
    if (
$adduser)
    {
    
// Registration Success
    
header'Location: user.php?message=<h5>New '.$_POST['username'].'user added<h5>&Type=success');
    
    } else
    {
    
// Registration Failed
    
header'Location: user.php?message=Error while adding user!!!!!&Type=error');
    }
    }
    
?>

------

   <?php 
       
if(isset($_GET['sortby'])) {
           
          
$sort_type $_GET['sortby'] ;
          
$order $_GET['order'] ;
          
          
$bids $touchObj->list_all_bids($sort_type$order);
          
                        }      
           else {   
                  
$bids $touchObj->list_all_bids("bid_status""DESC");
                }         
                
                  
                foreach(
$bids as $bid ) {
                  
           
?>




 <?php echo $bid[bid_id]; ?>


 <?php  ?>

Get all the images from a directory
177
<?php
    $directory 
"wp-content/themes/" get_template() . "/imgs/";
    
$images glob($directory "*.jpg");
    
$count 1;
    foreach(
$images as $image) {  ?>
        <img src="<?php echo site_url().'/'.$image;?>" alt="" <?php if($count==1){ echo 'class="active"'; }?>  />
<?php $count++; } ?>

Include specific post types on search results
178
<?php
function search_filter($query) {
  if ( !
is_admin() && $query->is_main_query() ) {
    if (
$query->is_search) {
      
$query->set('post_type', array( 'post''page' ) );
    }
  }
}
add_action('pre_get_posts','search_filter');
?>

Quesry post type according to the taxonomy
179
<?php
$args 
= array(
    
'post_type' => 'questions',
    
'showposts'=> 10,
    
'orderby'=> 'name',
    
'tax_query' => array(
        array(
            
'taxonomy' => 'question_category',
            
'field' => 'slug',
            
'terms' => 'laser'
            
)
        )
    );
    
$wp_query = new WP_Query$args );
    while( 
$wp_query->have_posts() ) : $wp_query->the_post(); 
    
the_title();
    endwhile; 
wp_reset_query();
?>

Get the grand parent page of a page
180
<?php
$yourid 
501;
$parent get_post_ancestors($yourid);
echo 
"<pre>"print_r($parent); echo "</pre>";
?>

Order of precedence for the default files on server
181
1.    default.asp
2.    default.html
3.    default.htm
4.    default.aspx
5.    default.php
6.    default.shtm
7.    index.html
8.    index.htm
9.    index.asp
10.    index.php
11.    index.shtml
12.    index.shtm
13.    home.html
14.    home.htm
15.    home.shtml
16.    home.shtm
17.    welcome.html
18.    welcome.asp

wp_nav_menu change sub-menu class name
182
Functions.php
---------------------
class My_Walker_Nav_Menu extends Walker_Nav_Menu {
  function start_lvl(&$output, $depth) {
    $indent = str_repeat("t", $depth);
    $output .= "n$indent<ul class="my-sub-menu">n";
  }
}

call walker along with wp_nav_menu
-------------------------------------------------
'walker' => new My_Walker_Nav_Menu()

Hover Div on a Another Div
183
$(document).ready(function () {
  $('.infiniteCarousel').infiniteCarousel();
  
  
    $(".clHover").hover(function(){
        
        //$(this).parent("div").('.collHover').css({visibility: "visible"}).show(268);
                
                $(this).parent(".collec_text").find(".collHover").css({visibility: "visible",display: "none"}).show(268);
                
        },function(){
        $(this).parent(".collec_text").find(".collHover").css({visibility: "hidden"}).show(268);
        });
  
});

Customize WP search results to display only pages, posts, post type and hide some pages etc.
184
<?php
function search_filter($query) {
  if ( !
is_admin() && $query->is_main_query() ) {
    if (
$query->is_search) {
      
$query->set( array(
            
'post_type', array( 
                
'post'
                
'page',
                
'tribe_events'
            
),
            
'post__not_in', array(4165
        )
      );
    }
  }
}
add_action('pre_get_posts','search_filter');
?>

List all categories with their posts
185
<?php
    $cats 
get_categories();
    foreach (
$cats as $cat) {
    
$cat_id$cat->term_id;
    echo 
"<h2 class='categoryTitle'>".$cat->name."</h2><ul>";
        
query_posts("cat=$cat_id&posts_per_page=100");
        if (
have_posts()) : while (have_posts()) : the_post(); ?>
            <li><a href="<?php the_permalink();?>"><?php the_title(); ?></a></li>
        <?php endwhile; endif; ?>
    </ul>
<?php ?>

Display post type categories with their posts
186
<?php
                            $cat_args 
= array (
                              
'taxonomy' => 'product-category',
                              
'hide_empty' => 0,
                            );
                            
$categories get_categories $cat_args );
                            foreach ( 
$categories as $category ) {
                              echo 
'<h3>' .$category->name.'</h3> <ul>';
                                
$args = array(
                                
'post_type' => 'axi_product',
                                
'tax_query' => array(
                                    array(
                                    
'taxonomy' => 'product-category',
                                    
'field' => 'id',
                                    
'terms' => $category->term_id
                                    
)
                                )
                                );
                                
$cat_query = new WP_Query$args );
                                while ( 
$cat_query->have_posts() ) : $cat_query->the_post(); ?>
                                    <li>
                                      <a href="<?php the_permalink();?>"><?php the_title(); ?></a>
                                    </li>
                                <?php endwhile; wp_reset_postdata();
                                echo 
'</ul>';
                            }
                        
?>

Get terms for all custom taxonomies
187
Add to functions.php

<?php
// get taxonomies terms links
function custom_taxonomies_terms_links(){
  
// get post by post id
  
$post get_post$post->ID );

  
// get post type by post
  
$post_type $post->post_type;

  
// get post type taxonomies
  
$taxonomies get_object_taxonomies$post_type'objects' );

  
$out = array();
  foreach ( 
$taxonomies as $taxonomy_slug => $taxonomy ){

    
// get the terms related to post
    
$terms get_the_terms$post->ID$taxonomy_slug );

    if ( !empty( 
$terms ) ) {
      
$out[] = "<h2>" $taxonomy->label "</h2>n<ul>";
      foreach ( 
$terms as $term ) {
        
$out[] =
          
'  <li><a href="'
        
.    get_term_link$term->slug$taxonomy_slug ) .'">'
        
.    $term->name
        
"</a></li>n";
      }
      
$out[] = "</ul>n";
    }
  }

  return 
implode(''$out );
}
?>

Call it:
--------------------
<?php echo custom_taxonomies_terms_links(); ?>

Add custom meta fields to WP registration and display them on user page on admin panel
188
<?php
add_action
'show_user_profile''my_show_extra_profile_fields' );
add_action'edit_user_profile''my_show_extra_profile_fields' );

function 
my_show_extra_profile_fields$user ) { ?>
    <h3>Extra profile information</h3>
    <table class="form-table">
        <tr>
            <th><label for="address">Address</label></th>
            <td>
                <input type="text" name="address" id="address" value="<?php echo esc_attrget_the_author_meta'address'$user->ID ) ); ?>" class="regular-text" /><br />
                <span class="description">Please enter your address.</span>
            </td>
        </tr>
        
        <tr>
            <th><label for="street">Street</label></th>
            <td>
                <input type="text" name="street" id="street" value="<?php echo esc_attrget_the_author_meta'street'$user->ID ) ); ?>" class="regular-text" /><br />
                <span class="description">Please enter your street.</span>
            </td>
        </tr>
    </table>
<?php }


add_action('register_form','show_first_name_field');
add_action('register_post','check_fields',10,3);
add_action('user_register''register_extra_fields');
function 
show_first_name_field()
{
?>
    <p>
    <label>Address<br/>
    <input id="address" type="text" tabindex="30" size="25" value="<?php echo $_POST['address']; ?>" name="address" />
    </label>
    </p>
    <p>
    <label>Street<br/>
    <input id="street" type="text" tabindex="30" size="25" value="<?php echo $_POST['street']; ?>" name="street" />
    </label>
    </p>
<?php
}
function 
check_fields $login$email$errors )
{
    global 
$address$street$state$city$zip;
    
    if ( 
$_POST['address'] == '' )    {
        
$errors->add'empty_realname'"<strong>ERROR</strong>: Please Enter your address field" );
    }
    else{
        
$address $_POST['address'];
    }
    
    if ( 
$_POST['street'] == '' ){
        
$errors->add'empty_realname'"<strong>ERROR</strong>: Please Enter your street field" );
    }
    else {
        
$street $_POST['street'];
    }
}
function 
register_extra_fields $user_id$password ""$meta = array() )
{
    
update_user_meta$user_id'address'$_POST['address'] );
    
update_user_meta$user_id'street'$_POST['street'] );
}
?>

Display terms of current post type
189
$term_lists = wp_get_post_terms($post->ID, 'product_cat');

Display only one category of current post
190
<?php
$category 
get_the_category();
echo 
$category[0]->cat_name;
?>

Query Post With a Meta Key - Show Post in Home page based on cutom field
191
<?php 
                    query_posts
(
                      array( 
'post_type' => 'product',
                      
'taxonomy' =>'product_category',
                      
'meta_query' => array(
                                      array (
                                        
'key' => 'show_home',
                                        
'value'=>'1'
                                    
)
                            )));
                            
                    
?>

Get child theme directory URL
192
<?php echo get_stylesheet_directory_uri();?>

Change "Posts" to "News" in admin panel
193
function revcon_change_post_label() {
    global $menu;
    global $submenu;
    $menu[5][0] = 'News';
    $submenu['edit.php'][5][0] = 'News';
    $submenu['edit.php'][10][0] = 'Add News';
    $submenu['edit.php'][16][0] = 'News Tags';
    echo '';
}
function revcon_change_post_object() {
    global $wp_post_types;
    $labels = &$wp_post_types['post']->labels;
    $labels->name = 'News';
    $labels->singular_name = 'News';
    $labels->add_new = 'Add News';
    $labels->add_new_item = 'Add News';
    $labels->edit_item = 'Edit News';
    $labels->new_item = 'News';
    $labels->view_item = 'View News';
    $labels->search_items = 'Search News';
    $labels->not_found = 'No News found';
    $labels->not_found_in_trash = 'No News found in Trash';
    $labels->all_items = 'All News';
    $labels->menu_name = 'News';
    $labels->name_admin_bar = 'News';
}
 
add_action( 'admin_menu', 'revcon_change_post_label' );
add_action( 'init', 'revcon_change_post_object' );

Inject cutom menu item to a WP menu
194
function add_loginout_link( $items, $args ) {
    if (is_user_logged_in() && $args->theme_location == 'main_nav') {
        $home = get_bloginfo('url');
        $items .= '<li><a href="'. wp_logout_url($home) .'">Log Out</a></li>';
    }
    elseif (!is_user_logged_in() && $args->theme_location == 'main_nav') {
        $items .= '<li><a href="#" class="loginToggle">Member Login</a></li>';
    }
    return $items;
}
add_filter( 'wp_nav_menu_items', 'add_loginout_link', 10, 2 );

Expire a PDF after certain time
195
var curDate = new Date();
var finalDate = new Date("2/21/2014");
if(finalDate.getTime() < curDate.getTime()) {
    app.alert("This document is no longer valid.  Please contact the author");
    this.closeDoc(true);
}

Shortcodes in Text Widgets
196
<?php add_filter'widget_text''do_shortcode' ); ?>

Add a custom meta for all the post types with a dropdown menu of all pages
197
In functions
---------------------------------
<?php add_action'add_meta_boxes''ab_custom_meta_box' );
function 
ab_custom_meta_box($post){
    
add_meta_box('ab_meta_box''Select Page''custom_selected_page'$post->post_type'side' 'high');
}
add_action('save_post''so_save_metabox');
function 
so_save_metabox(){ 
    global 
$post;
    if(isset(
$_POST["custom_page_class"])){
        
$meta_element_class $_POST['custom_page_class'];
        
update_post_meta($post->ID'custom_selected_page'$meta_element_class);
    }
}
function 
custom_selected_page($post){
    
$pages get_pages();
    
$meta_element_class get_post_meta($post->ID'custom_selected_page'true);
    
$choosen get_post_meta($post->ID"custom_selected_page"$single true); 
    
?>   
    <label>Choose the page to display:  </label>
    <select name="custom_page_class" id="custom_page_class">
        <?php foreach($pages as $page) { 
            
$selected $choosen == $page->ID 'selected="selected"' '';
            echo 
'<option value="'.$page->ID.'" '.$selected.'>'.$page->post_title.'</option>';
        } 
?>
    </select>
<?php ?>


Call it
--------------
get_post_meta($post->ID, "custom_selected_page", $single = true); 

Change "Posts" to "Products"
198
/*change POSTS to PRODUCTS */
function change_post_menu_label() {
global $menu;
global $submenu;
$menu[5][0] = 'Products';
$submenu['edit.php'][5][0] = 'Products';
$submenu['edit.php'][10][0] = 'Add Products';
$submenu['edit.php'][15][0] = 'Status'; // Change name for categories
$submenu['edit.php'][16][0] = 'Labels'; // Change name for tags
echo '';
}

function change_post_object_label() {
    global $wp_post_types;
    $labels = &$wp_post_types['post']->labels;
    $labels->name = 'Products';
    $labels->singular_name = 'Product';
    $labels->add_new = 'Add Product';
    $labels->add_new_item = 'Add Product';
    $labels->edit_item = 'Edit Products';
    $labels->new_item = 'Product';
    $labels->view_item = 'View Product';
    $labels->search_items = 'Search Products';
    $labels->not_found = 'No Products found';
    $labels->not_found_in_trash = 'No Products found in Trash';
}
add_action( 'init', 'change_post_object_label' );
add_action( 'admin_menu', 'change_post_menu_label' );

Show meta box if a specific page template is used (jQuery)
199
add_action( 'admin_head-post.php', 'metabox_switcher' );
add_action( 'admin_head-post-new.php', 'metabox_switcher' );

function metabox_switcher( $post ){

        #Locate the ID of your metabox with Developer tools
        $metabox_selector_id = 'about-banner-image-meta';
        echo '
            <style type="text/css">
                /* Hide your metabox so there is no latency flash of your metabox before being hidden */
                #'.$metabox_selector_id.'{display:none;}
            </style>
            <script type="text/javascript">
                jQuery(document).ready(function($){

                    //You can find this in the value of the Page Template dropdown
                    var templateName = 'template-about.php';

                    //Page template in the publishing options
                    var currentTemplate = $('#page_template');

                    //Identify your metabox
                    var metabox = $('#'.$metabox_selector_id.'');

                    //On DOM ready, check if your page template is selected
                    if(currentTemplate.val() === templateName){
                        metabox.show();
                    }

                    //Bind a change event to make sure we show or hide the metabox based on user selection of a template
                    currentTemplate.change(function(e){
                        if(currentTemplate.val() === templateName){
                            metabox.show();
                        }
                        else{
                            //You should clear out all metabox values here;
                            metabox.hide();
                        }
                    });
                });
            </script>
        ';
}

Shortcode to display custom post type
200
function abScrollingTestimonials() {
    ob_start();
    $data = '<div class="testiScroller">';
        $query = new WP_Query('post_type=testimonial&showposts=5&orderby=rand');
            while( $query->have_posts() ):$query->the_post();
            $data .= '<div class="singleTestimonial" id="testomial-'.get_the_ID().'">';
                $data .= ab_improved_excerpt_nop();
                $data .= '<div class="clientDetails">- '.get_the_title().'<span>('.get_the_excerpt().')</span></div>';
            $data .= '</div>';
        endwhile; wp_reset_postdata();
    $data .= '</div>';
    return $data;
 }
add_shortcode('fadingTestimonials','abScrollingTestimonials');

Hide specific user from Wordpress backend
201
add_action('pre_user_query','pre_user_query');
function pre_user_query($user_search) {
  global $current_user;
  $username = $current_user->user_login;

  if ($username == 'admin') { 

  }

  else {
    global $wpdb;
    $user_search->query_where = str_replace('WHERE 1=1',
      "WHERE 1=1 AND {$wpdb->users}.user_login != 'admin'",$user_search->query_where);
  }
}

Gettinga ttached images of a page
202
$images = get_children("post_parent=".$page_id."&post_type=attachment&post_mime_type=image");
        foreach($images as $image) {
              $url = wp_get_attachment_image_src($image->ID, 'medium');
              $caption = $image->ID;
              echo('<li><img alt="'.$caption.'" src="'.$url[0].'" /></li>' . "n");
              
        }

Short Code With Parameter Content Styling
203
<?php
function coregnie_list_ul$atts$content null ) {

    
extract(shortcode_atts(array(
      
'style' => 'cg_list',
   ), 
$atts));

   return 
'<ul class=cg_list_'.$style.' >'.do_shortcode($content).'</ul>';
}
add_shortcode('ul''coregnie_list_ul');

function 
coregnie_list_li$atts$content null ) {
   return 
'<li>'.do_shortcode($content).'</li>';
}
add_shortcode('li''coregnie_list_li');

?>

Option Field View based on template
204
    // ===========================    
    // Meta-Boxes Switcher 
    // Set the page-template [select] field to toggle which meta-box shows up
    // ===========================    
    $('div#blog_template_options').hide();
    $('#page_template').change(function() {
        $('#blog_template_options').toggle($(this).val() == 'template-blog.php');
    }).change();

Titan Framework Meta Box only for specific pages.
205
Add funtion to function.php
-----------------------------------------

<?php
add_action
'admin_head''admin_pageId_check' );
function 
admin_pageId_check() {
    
$cr_page_id =  get_the_ID();
}

?>

Then Create Meta like:
---------------------------------------------------
<?php
  
if($cr_page_id ) {  // Our misin page id to view mata only for this page
        
                
$titan TitanFramework::getInstance'genietheme' );
                
$pageMetaBox $titan->createMetaBox( array(
                    
'name' => 'Our Mission Page Video',
                ) );

                 
$pageMetaBox->createOption( array(
                        
'name' => 'Video Code',
                         
'id' => 'video_code',
                        
'type' => 'text',
                         
'desc' => 'Ex: Enter video Links',
                        ) ); 
                 
                }

    }
?>

Twitter Widget Demo
206
<a class="twitter-timeline" href="https://twitter.com/google" data-widget-id="581380877956960256">Tweets by @google</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>

WPML Supported Query with Page ID
207
<?php  
$query 
= new WP_Query'page_id='.icl_object_id(221,'page',true)  ); 
 while ( 
$query->have_posts() ) : $query->the_post(); 
?> 
<div class="yellow_content">  
<?php the_content(); ?> 
 <?php endwhile; ?> 
 <?php wp_reset_query();?>  
</div> 

Posty Type Full Code
208
<?php
function create_post_type() {
  
$labels = array(
    
'name'               => 'Projects',
    
'singular_name'      => 'Project',
    
'menu_name'          => 'Projects',
    
'name_admin_bar'     => 'Project',
    
'add_new'            => 'Add New',
    
'add_new_item'       => 'Add New Project',
    
'new_item'           => 'New Project',
    
'edit_item'          => 'Edit Project',
    
'view_item'          => 'View Project',
    
'all_items'          => 'All Projects',
    
'search_items'       => 'Search Projects',
    
'parent_item_colon'  => 'Parent Project',
    
'not_found'          => 'No Projects Found',
    
'not_found_in_trash' => 'No Projects Found in Trash'
  
);

  
$args = array(
    
'labels'              => $labels,
    
'public'              => true,
    
'exclude_from_search' => false,
    
'publicly_queryable'  => true,
    
'show_ui'             => true,
    
'show_in_nav_menus'   => true,
    
'show_in_menu'        => true,
    
'show_in_admin_bar'   => true,
    
'menu_position'       => 5,
    
'menu_icon'           => 'dashicons-admin-appearance',
    
'capability_type'     => 'post',
    
'hierarchical'        => false,
    
'supports'            => array( 'title''editor''author''thumbnail''excerpt''comments' ),
    
'has_archive'         => true,
    
'rewrite'             => array( 'slug' => 'projects' ),
    
'query_var'           => true
  
);

  
register_post_type'sm_project'$args );
}

?>

Change URL of wordpress site uisng mysql
209
UPDATE wp_options SET option_value = replace(option_value, 'http://old.com', 'http://new.com') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET guid = replace(guid, 'http://old.com','http://new.com');
UPDATE wp_posts SET post_content = replace(post_content, 'http://old.com', 'http://new.com');
UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://old.com','http://new.com');

MD5 Hash for Common Series
210
$1$cVGDPvbX$sWq3.aDDE6agy56kChgBm1

Zip a folder Using Php and FTP only
211
<?
// increase script timeout value
ini_set("max_execution_time"300);
// create object
$zip = new ZipArchive();
// open archive
if ($zip->open("my-archive.zip"ZIPARCHIVE::CREATE) !== TRUE) {
die (
"Could not open archive");
}
// initialize an iterator
// pass it the directory to be processed
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("vantage/"));
// iterate over the directory
// add each file found to the archive
foreach ($iterator as $key=>$value) {
$zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");
}
// close and save archive
$zip->close();
echo 
"Archive created successfully.";
?>

Contact Form 7 Sequence Generator
212
SOURCE: https://github.com/aztecweb/contact-form-7-sequence-generator/blob/master/contact-form-7-sequence-generator.php


function wpcf7sg_generate_number( $wpcf7_data ) {
    $properties = $wpcf7_data->get_properties();
    $shortcode = '[sequence-generator]';
    $mail = $properties['mail']['body'];
    $mail_2 = $properties['mail_2']['body'];
    if( preg_match( "/{$shortcode}/", $mail ) || preg_match( "/[{$shortcode}]/", $mail_2 ) ) {
        $option = 'wpcf7sg_' . $wpcf7_data->id();
        $sequence_number = (int)get_option( $option ) + 1;
        update_option( $option, $sequence_number );
        
        $properties['mail']['body'] = str_replace( $shortcode, $sequence_number, $mail );
        $properties['mail_2']['body'] = str_replace( $shortcode, $sequence_number, $mail_2 );
        
        $wpcf7_data->set_properties( $properties );
    }
}
add_action( 'wpcf7_before_send_mail', 'wpcf7sg_generate_number' );

HTML Under Construction Page
213
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Website coming soon</title>

<style type="text/css">
body { margin:0px; padding:0px; background-color:#F5F5F5; font-family: sans-serif;}
.Main {
  background-color: #FFFFFF;
  border: 4px solid #E6E6E6;
  border-radius: 20px;
  margin: 100px auto 0;
  padding: 66px;
  text-align: center;
  width: 458px;
}
h1{ font-size:35px;}
p { font-size:16px;}
</style>
</head>

<body>
<div class="Main">
<center> 
<img src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDEyOCAxMjgiIHZlcnNpb249IjEuMSIgdmlld0JveD0iMCAwIDEyOCAxMjgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxnIGlkPSJMYXllcl8xIj48cmVjdCBmaWxsPSIjRjRGNUY1IiBoZWlnaHQ9IjE1MjAiIG9wYWNpdHk9IjAiIHdpZHRoPSI3MjcuOTM4IiB4PSItNTM5Ljk4NCIgeT0iLTczMSIvPjwvZz48ZyBpZD0iTGF5ZXJfMiI+PGc+PGNpcmNsZSBjeD0iNjQiIGN5PSI2NCIgZmlsbD0iI0Y1NEYzMyIgcj0iNjQiLz48Zz48ZGVmcz48Y2lyY2xlIGN4PSI2NCIgY3k9IjY0IiBpZD0iU1ZHSURfMzFfIiByPSI2NCIvPjwvZGVmcz48Y2xpcFBhdGggaWQ9IlNWR0lEXzJfIj48dXNlIG92ZXJmbG93PSJ2aXNpYmxlIiB4bGluazpocmVmPSIjU1ZHSURfMzFfIi8+PC9jbGlwUGF0aD48cG9seWdvbiBjbGlwLXBhdGg9InVybCgjU1ZHSURfMl8pIiBmaWxsPSIjREQyQzI0IiBwb2ludHM9IjIwLjE2MSw5Ni4xMTkgNTIuMDM2LDEyOCAxMjgsMTI4IDEyOCw1Mi41MzYgMTA4LjExNSwzMi42MjIgICAgIi8+PC9nPjxwYXRoIGQ9Ik0xMDQuOTQ0LDk2Ljk0N0gyMy4wNTZjLTIuMjA5LDAtNC0xLjc5MS00LTRWMzUuMDUzYzAtMi4yMDksMS43OTEtNCw0LTRoODEuODg4YzIuMjA5LDAsNCwxLjc5MSw0LDQgICAgdjU3Ljg5NEMxMDguOTQ0LDk1LjE1NiwxMDcuMTUzLDk2Ljk0NywxMDQuOTQ0LDk2Ljk0N3oiIGZpbGw9IiNGRkZGRkYiLz48Zz48cGF0aCBkPSJNMTA4Ljk0NCw0Mi4wNTR2LTcuMDAxYzAtMi4yMDktMS43OTEtNC00LTRIMjMuMDU2Yy0yLjIwOSwwLTQsMS43OTEtNCw0djcuMDAxSDEwOC45NDR6IiBmaWxsPSIjRTFFM0U5Ii8+PC9nPjxjaXJjbGUgY3g9IjI1IiBjeT0iMzYuNTUzIiBmaWxsPSIjRjI0QjQ1IiByPSIzIi8+PGNpcmNsZSBjeD0iMzQiIGN5PSIzNi41NTMiIGZpbGw9IiNGRkIyMDIiIHI9IjMiLz48Y2lyY2xlIGN4PSI0My4wMDEiIGN5PSIzNi41NTMiIGZpbGw9IiM0Q0JCNDEiIHI9IjMiLz48Zz48ZGVmcz48cGF0aCBkPSJNMTA0Ljk0NCw5Ni45NDdIMjMuMDU2Yy0yLjIwOSwwLTQtMS43OTEtNC00VjM1LjA1M2MwLTIuMjA5LDEuNzkxLTQsNC00aDgxLjg4OGMyLjIwOSwwLDQsMS43OTEsNCw0ICAgICAgdjU3Ljg5NEMxMDguOTQ0LDk1LjE1NiwxMDcuMTUzLDk2Ljk0NywxMDQuOTQ0LDk2Ljk0N3oiIGlkPSJTVkdJRF8zM18iLz48L2RlZnM+PGNsaXBQYXRoIGlkPSJTVkdJRF80XyI+PHVzZSBvdmVyZmxvdz0idmlzaWJsZSIgeGxpbms6aHJlZj0iI1NWR0lEXzMzXyIvPjwvY2xpcFBhdGg+PHBvbHlnb24gY2xpcC1wYXRoPSJ1cmwoI1NWR0lEXzRfKSIgZmlsbD0iI0UxRTNFOSIgb3BhY2l0eT0iMC44IiBwb2ludHM9IjMwLjg2Niw3MC44NTUgNTcuNDM4LDk3LjUgMTEwLDk3LjUgMTEwLDc5LjU2MyAgICAgIDk3LjEzNCw2Ni42NjMgODQuNDY5LDYzLjcxOSA3MS43OTUsNTEuMDU2IDY0LjM3Niw2Ny4xODggNTMuNDc1LDU2LjMgMzEuOTM3LDY4LjgzICAgICIvPjwvZz48Zz48cGF0aCBkPSJNMzAuODY2LDY2LjgwNEw1My40NzUsNTYuM3Y0Ljk5M2wtMTcuMDk5LDcuNDl2MC4wOTRsMTcuMDk5LDcuNDg5djQuOTkzTDMwLjg2Niw3MC44NTVWNjYuODA0eiIgZmlsbD0iIzUzODk5RiIvPjxwYXRoIGQ9Ik01Ni45NTgsODUuMjA2bDEwLjA4LTM0LjE1aDQuNzU4bC0xMC4wODEsMzQuMTVINTYuOTU4eiIgZmlsbD0iIzUzODk5RiIvPjxwYXRoIGQ9Ik05Ny4xMzQsNzAuOTk3TDc0LjUyNSw4MS4zNTl2LTQuOTkzTDkyLDY4Ljg3N3YtMC4wOTRsLTE3LjQ3Ni03LjQ5VjU2LjNsMjIuNjA5LDEwLjM2M1Y3MC45OTd6IiBmaWxsPSIjNTM4OTlGIi8+PC9nPjwvZz48L2c+PC9zdmc+" width="200"/>
</center>
<h1>  Omoobaeledua.com</h1>
<p>
This website is under construction </p>
</div>


</body>
</html>

e*zxVEDC9vCeX8z=92eTgW
214
$1$0MM0JBr6$yzMDbkrBF6JJHwyY1/yZB0

Wordpress Installation Over SSH
215
ssh username@domain.com -p 22

cd public_html/blogdemo/

wget http://wordpress.org/latest.tar.gz
tar xfz latest.tar.gz


mv wordpress/* ./

rmdir ./wordpress/
rm -f latest.tar.gz

Disable a Single Plugin Update in WordPress
216
<?php

// To disable Event Plugin update- This plugin code is edited by developer

function disable_event_plugin_updates$value ) {
   if( isset( 
$value->response['the-events-calendar/the-events-calendar.php'] ) ) {        
      unset( 
$value->response['the-events-calendar/the-events-calendar.php'] );
    }
    return 
$value;
 }
add_filter'site_transient_update_plugins''disable_event_plugin_updates' );


?>

Get ACF fields of the current post for the REST API field
217
/**
 * Create REST field of ACF values for WordPress REST API
 */
function create_acf_fields_key_for_rest_api() {
    register_rest_field(
        [ 'post', 'page' ], // add post types here
        'acf_fields', // name of the field
        array(
            'get_callback'    => 'get_acf_fields_for_api',
            'update_callback' => null,
            'schema'          => null,
        )
    );
}
add_action( 'rest_api_init', 'create_acf_fields_key_for_rest_api' );

/**
 * Get ACF fields of the current post for the REST API field
 *
 * @param array $object post object array
 * @return array acf fields related to current post
 */
function get_acf_fields_for_api( $object ) {
    $data = get_fields( get_the_ID() );
    return $data ?: false;
}

Get Data From Rest in WP
218

<?php
// Function
function coregenie_user_api() {
    

    
$response wp_remote_get'https://malayalamsubtitles.org/wp-json/wp/v2/posts' );
    try {
 
        
// Note that we decode the body's response since it's the actual JSON feed
        
$json json_decode$response['body'] );
 
    } catch ( 
Exception $ex ) {
        
$json null;
    } 
// end try/catch
 
    
return $json;
    

}
?>

<?php
// Usage
if ( null == ( $users coregenie_user_api( ) ) ) {
    
$html 'There was a problem communicating with the  API..';
} else {

//var_dump($users); 

    
if( ! empty( $users ) ) {
    
        echo 
'<ul>';
        foreach( 
$users as $data_item ) {
            echo 
'<li>';
                echo 
'<a href="' esc_url$data_item->guid->rendered ) . '">' $data_item->title->rendered '</a>';
            echo 
'</li>';
        }
        echo 
'</ul>';
    }

?>