Back to top

WordPress Documentation

Thank you so much for Installing

WordPress - Open Source!

This document covers the installation and use of this WordPress and reveals answers to common problems and issues - I encourage you to read this document thoroughly if you are experiencing any difficulties.

Get started!


 

Getting started

Download Latest version of wordpress from http://wordpress.org/download/

To install this theme you must have a working version of WordPress already installed. For information in regard to installing the WordPress platform, please see the WordPress Codex - http://codex.wordpress.org/Installing_WordPress

 

Installation

Upload via ftp:

Choose a theme. Firstly, unzip the "WordPress_Theme".zip file to a directory on your computer. Open this archive and upload to your server via ftp to the   /themes/ directory on your Wordpress installation. (wp-content > themes)

 

Upload via Wordpress admin:

Go to your Wordpress admin, and in the Appearance-panel, choose Add New Themes. Click Add new. Upload the "WordPress_Theme".zip. if you have a "missing stylesheet" issue you are uploading the wrong file!

Installing WordPress  http://codex.wordpress.org/Installing_WordPress

 

Activation

Once you have uploaded the theme, activate your theme in Appearance > Themes. 

Using Themes http://codex.wordpress.org/Using_Themes

 

Install sample content

You can install sample content by importing XML file.

  1. Go to Appearance > Import/Export
  2. Select the .gz file you downloaded (don't open this file! only upload it);
  3. Click to import

Introduction

A semantic personal publishing platform with a focus on aesthetics, web standards, and usability. WordPress is web software you can use to create a beautiful website or blog. WordPress is a free and open source blogging tool and a dynamic content management system (CMS) based on PHP and MySQL. It has many features including a plug-in architecture and a template system.


Files


ID File Name Description
1 header.php Header part usually logo & menu
2 Index.php Home page
3 footer.php Footer usually a menu or copyright
4 sidebar.php Common code to execute in left or right of innerpages
5 single.php Innerpage - Post
6 page.php Innerpage - Page
7 functions.php Write functions for theme as well as custom codes
8 style.css CSS style for webpage
9 category.php General template for display posts in categories
10 taxonomy.php Taxonomy Page
11 archives.php General template for display posts in categories
12 date.php Date Page
13 author.php Pages for the Users
14 tag.php Tag Page
15 comments.php Comments Page
16 404.php Error Page

Lists

  • Pages
  • Posts
  • Categories and Tags
  • Plugins
  • Widget
  • Links
  • Media
  • Custom Posts
  • Custom fields
  • Comments

Info


Style Sheet

<?php bloginfo( 'stylesheet_url' ); ?>

Character Set

<?php bloginfo('charset'); ?>

Website URL

<?php bloginfo( 'url' ); ?>

Website Path

<?php bloginfo( 'template_url' ); ?>/PATH

Title

<?php bloginfo('name');?>

Description

<?php bloginfo('description'); ?>

Header

<?php get_header(); ?>

Sidebar

<?php get_sidebar(); ?>

Footer

<?php get_footer(); ?>

 


Wordpress Template Hierarchy

Template

 

Setting up pages and posts

Setting up the home page

To start with Theme you have to:

  • Create a new page, and assign it the template 'home';
  • else edit in index.php

 

It's important that Wordpress is set up to display a static page as home page. You set this in Settings > Reading. Chose 'static page' and select the page you created for the home in the select menu.


 


Reserved Terms

Avoiding the following reserved terms is particularly important if you are passing the term through the $_GET or $_POST array. Doing so can cause WordPress to respond with a 404 error without any other hint or explanation.

  • attachment
  • attachment_id
  • author
  • author_name
  • calendar
  • cat
  • category
  • category__and
  • category__in
  • category__not_in
  • category_name
  • comments_per_page
  • comments_popup
  • customize_messenger_channel
  • customized
  • cpage
  • day
  • debug
  • error
  • exact
  • feed
  • hour
  • link_category
  • m
  • minute
  • monthnum
  • more
  • name
  • nav_menu
  • nonce
  • nopaging
  • offset
  • order
  • orderby
  • p
  • page
  • page_id
  • paged
  • pagename
  • pb
  • perm
  • post
  • post__in
  • post__not_in
  • post_format
  • post_mime_type
  • post_status
  • post_tag
  • post_type
  • posts
  • posts_per_archive_page
  • posts_per_page
  • preview
  • robots
  • s
  • search
  • second
  • sentence
  • showposts
  • static
  • subpost
  • subpost_id
  • tag
  • tag__and
  • tag__in
  • tag__not_in
  • tag_id
  • tag_slug__and
  • tag_slug__in
  • taxonomy
  • tb
  • term
  • theme
  • type
  • w
  • withcomments
  • withoutcomments
  • year

Setting up a Page Template

You can create page template say "Gallery" for Gallery Page:

 

Custom Page Template

  1. Create new php file or duplicate existing page
  2. Add the below code in header
  3. <?php
    /*
    Template Name: My Custom Page
    */
    ?>
    
  4. Save the file

NOTE: Name of the file does not affect any thing.

"Gallery page" Template is made and is very easy to set.

  1. Make a new page, and give it a title (like 'Gallery' or 'My pictures');
  2. Chose the template 'gallery' for this page;
  3. Publish.

 

Specialized Page Template

Create a template for one Page: For more extensive changes, intended for just one specific Page, you can create a specialized template file, named with that Page's slug or ID:

  • page-{slug}.php
  • page-{ID}.php

For example: Your About page has a slug of 'about' and an ID of 6. If your active Theme's folder has a file named page-about.php or page-6.php, then WordPress will automatically find and use that file to render the About page.

To be used, specialized page templates must be in your active Theme's folder:

/wp-content/themes/my-theme/

A specialized page template file can not be in a sub-folder, nor, if using a Child Theme, in its Parent Theme's folder.

Setting up the menu

This theme uses wp-nav-menu for building menus. You find this in Appearance > Menus.

For more info on how to setup your menu in wp 3.0, see http://codex.wordpress.org/Appearance_Menus_SubPanel

 

Building the menu

  1. Go to Appearance > Menus
  2. Enter a name for your menu
  3. Click on Create Menu


  4. Now in the Theme Location select the menu you just created
  5. Click on Save


  6. Now tick the pages you want to add to menu and click Add to Menu

When you added all pages to your menu, you can drag/drop and order pages.


Building the megamenu

Before you have to add the pages to your menu. After this, if you want to assign the megamenu style to the page, you have to use the CSS CLASSES megamenu. (To have it open the Screen Options tab on the top right and tick Css Classes):

 

To set the number of columns you want to create in your megamenu, you have to add columns-N (N is the number of columns) after the megamenu class. By default the megamenu have 3 columns. You can use min 1 column and max 5 columns.

megamenu columns-5

 

In our forum you can find a video that can help you to set the megamenu exactly our demo.

Walker_Nav_Menu

Custom walker object to use (Note: You must pass an actual object to use, not a string

functions.php
<?php
class Walker_Page_Custom extends Walker_Nav_Menu {
/**
* @see Walker::start_lvl()
* @since 2.1.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of page. Used for padding.
*/
function start_lvl(&$output, $depth)
{
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<div class='menu_dropdown_block'>
    <div class='container'><ul class='menu_submenu'>\n";
}

/**
* @see Walker::end_lvl()
* @since 2.1.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of page. Used for padding.
*/
function end_lvl(&$output, $depth)
{
    $indent = str_repeat("\t", $depth);
    $output .= "$indent</ul><span class='clear'><!-- --></span></div><!--sub-mid -->
    <div class='sub-bottom'><!-- --></div><!--sub-bottom -->
    <span class='clear'><!-- --></span></div><!--sub -->\n";
} }
?>

 

Customize div in Nav Menu

functions.php
class Walker_Page_Custom extends Walker_Nav_Menu {
/**
 * @see Walker::start_lvl()
 * @since 2.1.0
 *
 * @param string $output Passed by reference. Used to append additional content.
 * @param int $depth Depth of page. Used for padding.
 */
function start_lvl(&$output, $depth) {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<div class='menu_dropdown_block'><div class='container'><ul class='menu_submenu'>\n";
}

/**
 * @see Walker::end_lvl()
 * @since 2.1.0
 *
 * @param string $output Passed by reference. Used to append additional content.
 * @param int $depth Depth of page. Used for padding.
 */
function end_lvl(&$output, $depth) {
    $indent = str_repeat("\t", $depth);
    $output .= "$indent</ul><span class='clear'><!-- --></span></div><!--sub-mid --><div class='sub-bottom'><!-- --></div><!--sub-bottom --><span class='clear'><!-- --></span></div><!--sub -->\n";
} }

 

Menu With Description and Image

functions.php
//menu description
class Menu_With_Description extends Walker_Nav_Menu {
    function start_el(&$output, $item, $depth, $args) {
        global $wp_query;
 
        $indent = ( $depth ) ? str_repeat( " ", $depth ) : '';
 
        $class_names = $value = '';
 
        $classes = empty( $item->classes ) ? array() : (array) $item->classes;
 
        $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
        $class_names = ' class="' . esc_attr( $class_names ) . '"';
 
        $output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';
 
        $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
        $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
        $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
        $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
 
        // get user defined attributes for thumbnail images
        $attr_defaults = array( 'class' => 'nav_thumb' , 'alt' => esc_attr( $item->attr_title ) , 'title' => esc_attr( $item->attr_title ) );
        $attr = isset( $args->thumbnail_attr ) ? $args->thumbnail_attr : '';
        $attr = wp_parse_args( $attr , $attr_defaults );
 
        $item_output = $args->before;
 
        // thumbnail image output
        $item_output .= ( isset( $args->thumbnail_link ) && $args->thumbnail_link ) ? '<a' . $attributes . '>' : '';
        $item_output .= apply_filters( 'menu_item_thumbnail' , ( isset( $args->thumbnail ) && $args->thumbnail ) ? get_the_post_thumbnail( $item->object_id , ( isset( $args->thumbnail_size ) ) ? $args->thumbnail_size : 'thumbnail' , $attr ) : '' , $item , $args , $depth );        
        $item_output .= ( isset( $args->thumbnail_link ) && $args->thumbnail_link ) ? '</a>' : '';
 
        // menu link output
        $item_output .= '<a'. $attributes .'>';
        $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
 
        // menu description output based on depth
        $item_output .= ( $args->desc_depth >= $depth ) ? '<br /><span class="sub">' . $item->description . '</span>' : '';
 
        // close menu link anchor
        $item_output .= '</a>';
        $item_output .= $args->after;
 
        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }
}
 
add_filter( 'wp_nav_menu_args' , 'my_add_menu_descriptions' );
function my_add_menu_descriptions( $args ) {
    $args['walker'] = new Menu_With_Description;
    $args['desc_depth'] = 0;
    $args['thumbnail'] = true;
    $args['thumbnail_link'] = false;
    $args['thumbnail_size'] = 'nav_thumb';
    $args['thumbnail_attr'] = array( 'class' => 'nav_thumb my_thumb' , 'alt' => 'test' , 'title' => 'test' );
 
    return $args;
}

 

Getting a menu Object

functions.php
function ag_get_theme_menu( $theme_location ) {
	if( ! $theme_location ) return false;
 
	$theme_locations = get_nav_menu_locations();
	if( ! isset( $theme_locations[$theme_location] ) ) return false;
 
	$menu_obj = get_term( $theme_locations[$theme_location], 'nav_menu' );
	if( ! $menu_obj ) $menu_obj = false;
 
	return $menu_obj;
}

 

Getting a menu Name

functions.php
function gm_get_theme_menu_name( $theme_location ) {
	if( ! $theme_location ) return false;
 
	$theme_locations = get_nav_menu_locations();
	if( ! isset( $theme_locations[$theme_location] ) ) return false;
 
	$menu_obj = get_term( $theme_locations[$theme_location], 'nav_menu' );
	if( ! $menu_obj ) $menu_obj = false;
	if( ! isset( $menu_obj->name ) ) return false;
 
	return $menu_obj->name;
}

The WP_Query Function

The function we used in the last section to set parameters for the is part of a very powerful WordPress function called WP_Query. This function can be used to make very specific WordPress loops based on a large number options.

The WP_Query function is placed before the loop. A nice aspect of this function is that all you have to do is place it before the loop and you don't have to change anything about the loop itself.

Here are a few of the most common WP_Query options:

  • author – Filters loop by author id
  • author_name – Filters author by user_nicename
  • cat – Filters loop by category id
  • category_name – Filters loop by category slug
  • tag – Filters loop by tag slug
  • p – Filters loop by page or post id
  • name – Filters loop by post slug
  • pagename – Filters loop by page slug
  • page_id – Filters loop by page if
  • post_parent – Filters loop by id of parent page
  • post_type – Filters loop by post type, including custom post types
  • posts_per_page – Determines how many posts are looped through
  • offset – Determines how many posts to offset the loop by
  • order – Determines whether the posts display in ascending or descending order
  • orderby – Filters what factor the posts are sorted by. Default is date, but can be changed to things like title or author
  • year – Filters loop by posts in a given year
  • monthnum – Filters loop by a month numner. i.e. 1 = January
  • day – Filters loop by a specific day of the month

Usually all of the parameters are passed to the WP_Query function as an array.

Here is an example of using the WP_Query function to display the content for a specific page.

<?php 

	$args = array( 
		'pagename' => 'about-us'
	);
	$the_query = new WP_Query( $args );

?>

<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

	<h1><?php the_title() ;?></h1>			
	<?php the_excerpt(); ?>

<?php endwhile; else: ?>

	<p>Sorry, there are no posts to display</p>

<?php endif; ?>

For a more complex example, we can look at how to display all of the posts published by a specific author in a custom post type called workshops. We will also filter the loop so that it orders the posts by the title and only displays workshops published in the year 2012.

<?php 

	$args = array( 
		'author_name' => 'zgordon',
		'orderby' => 'title',
		'post_type' => 'workshops'
		'year' => 2012
	);
	$the_query = new WP_Query( $args );

?>

<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

	<h1><?php the_title() ;?></h1>			
	<?php the_excerpt(); ?>

<?php endwhile; else: ?>

	<p>Sorry, there are no posts to display</p>

<?php endif; ?>

You can find out more about working with the WP_Query on the WordPress Codex.

Display Posts in a Category

Display using query_posts fuction

<?php
// The Query
query_posts( $args );

// The Loop
while ( have_posts() ) : the_post(); ?>

<!-- Do special_cat stuff... -->

<?php endwhile;

// Reset Query
wp_reset_query();
?>

or the simplest way to write the above code is

<?php
query_posts('cat=7&showposts=10&offset=3');
while (have_posts()) : the_post(); ?>

<!-- Do special_cat stuff... -->

<?php endwhile;
wp_reset_query();
?>

The arguments in query posts fuctions

<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
    'cat'      => 22, // or -22 to exclude 22 category
    'order'    => 'ASC' // or 'DESC'
    'posts_per_page' => 3, // -1 will return ALL posts from the category
    'paged' => $paged,
    
    'category_name' => 'special_cat',
    'orderby' => 'title', // name, date
    'year'     => $current_year,
    'monthnum' => $current_month,    
    'tag' => 'apples'+'oranges',
    'attachment_id' => 5
);
query_posts($args);
?>
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<a href="<?php the_permalink(); ?>">">
<?php the_title(); ?></a>
<?php the_content();
endwhile; endif; ?>
 

Query variables

Public 
  • attachment
  • attachment_id
  • author
  • author_name
  • cat
  • category_name
  • comments_popup
  • day
  • error
  • feed
  • hour
  • hour
  • m
  • minute
  • monthnum
  • name
  • p
  • page_id
  • paged
  • pagename
  • post_parent
  • post_type
  • preview
  • second
  • static
  • subpost
  • subpost_id
  • tag
  • tag_id
  • tb
  • w
  • year
Private 
  • category__in
  • category__not_in
  • category__and
  • post__in
  • post__not_in
  • tag__in
  • tag__not_in
  • meta_key
  • meta_value

A Comprehensive Beginners Guide to the WordPress Loop

The WordPress Loop is the code used to display main content and excerpts of content on WordPress sites. Often times the loop is used to "loop" through and display a number of posts titles and excerpts like on a blog listing page.

The loop is also the same code used to display the content and comments on a single post or main content on a single page such as the About page for a site.

When sites use custom post types and custom fields, the loop is also used to display the data.

We can see that the WordPress Loop is quite versatile and used to display a range of content on WordPress sites. The code used to create the loop is at its core quite simple, however, it can be customized to a very great extent.

The Basic Logic Behind the Loop

The loop starts with code that checks to see if the current page is supposed to display a listing of multiple posts or a single post or page. If the page is supposed to list blog posts then it will list out a title and excerpt for each post (this can be customized to display featured images or other content). If the page is a single page or single post then the loop will just display the content for that page.

If no posts are available or someone accesses a page that does not exist, the loop has an option to display a custom message informing the visitor there are no posts or the page does not exist (similar to what a 404 page does except customized to specific types of content).

Thanks to WordPress templates, the loop can be customized for just about every page or type of content on your site.

There are also ways that you can use multiple loops on one page to display different types of content or format content in different ways. For example, you can have the latest blog post with a featured image display larger at the top of the site and then have older posts listed below with just a title and excerpt.

Two Simple Examples of the Loop Explained

Here is what a simple example of the loop looks like to display a listing of blog posts.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <h2><?php the_title() ;?></h2>
    <?php the_post_thumbnail(); ?>
    <?php the_excerpt(); ?>
    <?php endwhile; else: ?>
    <p>Sorry, no posts to list</p>
<?php endif; ?>

Lines 1, 7, and 11 are the basic logic that separate the code for when there are blog posts and no blog posts. Lines 3, 4, 5 do the actual work of displaying the title, featured image, and excerpt.

In line 1, the part of code that reads while ( have_posts() ) : the_post(); is what programs the process of repeating for as many times as there are posts.

Note: Using pagination on a site is a way of limiting the number of posts that are looped through on a page. After the loop reaches the default number of posts to display (set under Settings > Reading > Blog pages show at most) it will show how many more pages are available.

When you use the loop to display a single post or page instead of list multiple ones, interestingly the loop doesn't change much.

Here is what a simple loop looks like for displaying a title and the main content for a page.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
	<h1><?php the_title() ;?></h1>
	<?php the_content(); ?>
<?php endwhile; else: ?>
	<p>Sorry, this page does not exist</p>
<?php endif; ?>

You'll notice that the only things that really changed was the thumbnail and excerpt became the main content. The reason the same loop works for multiple posts and for single ones is because of the while statement while ( have_posts() ) : the_post(). Depending on what template the loop is used in and what page is accessed, the while statement will determine how many times to loop through the code

What the Loop Can Display

There are a number of elements that the loop can display, such as the title, excerpt, main content. Below you can see a list of these common functions along with a short description and a link to more information about each function.

  • next_post_link – Displays a link to the post published chronologically after the current post
  • previous_post_link – Displays a link to the post published chronologically before the current post
  • the_category – Displays the category or categories associated to the post or page being viewed
  • the_author – Displays the author of the post or page
  • the_content – Displays the main content for a post or page
  • the_excerpt – Displays the first 55 words of a post's main content then with a [...] or read more link that goes to the full post. The length of excerpts can be controlled by using this slightly advanced method or by using the Excerpt field on the post edit page.
  • the_ID – Displays the ID for the post or page
  • the_meta – Used to display custom fields
  • the_shortlink – Displays a link to the page or post using the url of the site using the ID of the post or page
  • the_tags – Displays the tag or tags associated with the post
  • the_title – Displays the title of the post or page
  • the_time – Displays the time or date for the post or page. This can be customized using the standard php date function formatting

The loop can also use conditional statements to display different content based on a number of factors.

  • is_home() – Returns true if the current page is the homepage
  • is_admin() – Returns true if admin is logged in and visiting the site
  • is_single() – Returns true if page is displaying a single post
  • is_page() – Returns true if page is displaying a single page
  • is_page_template() – Can tell you if page is using a specific template. i.e. is_page_template('about-page.php')
  • is_category() – Returns true if page or post has a specified category. i.e. is_category('news');
  • is_tag() – Returns true if page or post has a specified tag
  • is_author() – Returns true if a specific author is logged in and visiting the site. i.e. is_author('zgordon')
  • is_search – Returns true if page is a search results page
  • is_404() – Returns true if page does not exist
  • has_excerpt() – Returns true if post or page has an excerpt

You can find a full list of all the WordPress Conditional Tags on the WordPress Codex.

Advanced Loop Example

Here is an example of an advanced loop using a number of the functions and conditional statements listed above. We won't go into detail on every part of the loop since most of the elements are described in detail above.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<article id="post-<?php the_ID(); ?>" <?php if(is_category('featured')): ?>class="featured-post"<?php endif; ?>>
	<h1><?php the_title() ;?></h1>		

	<p>
		Published on <?php the_time('M j, Y'); ?> 
		by <?php the_category(', '); ?>
		in <?php the_category(', '); ?>
	</p>

	<?php the_content(); ?>

	<?php comment_form(); ?>

	<div class="prev-next-links">
		<ul>
			<li><?php next_post_link(); ?></li>
			<li><?php previous_post_link(); ?></li>
		</ul>

	</div>

</article>

<?php endwhile; else: ?>

	<p>Sorry, this post does not exist</p>

<?php endif; ?>

Multiple Loops

In some situations you may need to use multiple loops on one page. In order to do this you will have to use the rewind_posts() function before using a second, third or fourth time (you can do as many loops on a page that you want, but each loop will require another request to the database, which can begin to slow down the load time of your pages.

Here is what the rewind post function looks like in action for listing blog posts.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

	<h1><?php the_title() ;?></h1>		

	<?php the_excerpt(); ?>

<?php endwhile; else: ?>

	<p>Sorry, there are no posts to display</p>

<?php endif; ?>

<?php rewind_posts(); ?>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

	<h1><?php the_title() ;?></h1>		

	<?php the_excerpt(); ?>

<?php endwhile; else: ?>

	<p>Sorry, there are no posts to display</p>

<?php endif; ?>

Notice the rewind_posts() function on line 13.

The problem with this specific code is that each loop will output the exact same thing. In order to have the two loops display different things, we will have to give the loops some parameters telling each loop exactly what we want to display.

We can set parameters for loops using the query_posts() function. This function gives us a large number of parameters we can choose from to control what posts WordPress loops through. We'll look at some of these in detail in the next section, so for now let's just look at the code needed to display latest post in one format and then list the next three posts below it.

<?php query_posts('showposts=1&post_type=post'); ?>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

	<h1><?php the_title() ;?></h1>		
	<?php the_post_thumbnail(); ?>
	<?php the_excerpt(); ?>

<?php endwhile; else: ?>

	<p>Sorry, there are no posts to display</p>

<?php endif; ?>

<hr>

<?php rewind_posts(); ?>

<?php query_posts('showposts=3&offset=1&post_type=post'); ?>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

	<h2><?php the_title() ;?></h2>		

	<?php the_excerpt(); ?>

<?php endwhile; else: ?>

	<p>Sorry, there are no posts to display</p>

<?php endif; ?>

The magic here is happening on lines 1 and 19. Line 1 is telling WordPress to only display 1 post, which will automatically be the most recent one. On Line 19 we are telling WordPress to offset the posts by 1, which means it will not repeat the post output in the first loop. We are also limiting it to only displaying 3 posts.

Customize Posts / Adding Features

Change menu labels "Post" -> "Contacts" (admin area)

function change_post_menu_label() {
   global $menu;
   global $submenu;
   $menu[5][0] = 'Contacts';
   $submenu['edit.php'][5][0] = 'Contacts';
   $submenu['edit.php'][10][0] = 'Add Contacts';
   $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 = 'Contacts';
       $labels->singular_name = 'Contact';
       $labels->add_new = 'Add Contact';
       $labels->add_new_item = 'Add Contact';
       $labels->edit_item = 'Edit Contacts';
       $labels->new_item = 'Contact';
       $labels->view_item = 'View Contact';
       $labels->search_items = 'Search Contacts';
       $labels->not_found = 'No Contacts found';
       $labels->not_found_in_trash = 'No Contacts found in Trash';
   }
add_action( 'init', 'change_post_object_label' );
add_action( 'admin_menu', 'change_post_menu_label' );

 

Create A Better Meta Box In Post Editing Page

Before we start, make sure that you theme has functions.php file. All of our code will be pasted into this file. And our result will be like this:

Step 1. Define meta box with all needed fields

Open the functions.php file, and put the following code into it:

functions.php
$prefix = 'dbt_';
$meta_box = array(
    'id' => 'my-meta-box',
    'title' => 'Custom meta box',
    'page' => 'post',
    'context' => 'normal',
    'priority' => 'high',
    'fields' => array(
        array(
            'name' => 'Text box',
            'desc' => 'Enter something here',
            'id' => $prefix . 'text',
            'type' => 'text',
            'std' => 'Default value 1'
        ),
        array(
            'name' => 'Textarea',
            'desc' => 'Enter big text here',
            'id' => $prefix . 'textarea',
            'type' => 'textarea',
            'std' => 'Default value 2'
        ),
        array(
            'name' => 'Select box',
            'id' => $prefix . 'select',
            'type' => 'select',
            'options' => array('Option 1', 'Option 2', 'Option 3')
        ),
        array(
            'name' => 'Radio',
            'id' => $prefix . 'radio',
            'type' => 'radio',
            'options' => array(
                array('name' => 'Name 1', 'value' => 'Value 1'),
                array('name' => 'Name 2', 'value' => 'Value 2')
            )
        ),
        array(
            'name' => 'Checkbox',
            'id' => $prefix . 'checkbox',
            'type' => 'checkbox'
        )
    )
);

Let me explain the code:

In the beginning of the code, we defined a prefix:

$prefix = 'dbt_';

This prefix will be added before all of our custom fields. Using prefix can prevent us from conflicting with other scritps that also use custom fields.

The next variable $meta_box will hold all information about our meta box and all custom fields we need. Let's look at the first lines:

$meta_box = array( 'id' => 'my-meta-box-1', 'title' => 'Custom meta box', 'page' => 'post', 'context' => 'normal', 'priority' => 'high',

These are meta box's attributes:

  • id: just the ID of meta box, each meta box has an unique ID
  • title: the meta box title
  • page: The type of Write screen on which to show the meta box ('post', 'page', or 'link') (for WP 3.0, see note below)
  • context: The part of the page where the meta box should be shown ('normal', 'advanced' or (since 2.7) 'side')
  • priority: The priority within the context where the boxes should show ('high' or 'low')

For WordPress 3.0: If you're using custom post type in WordPress 3.0 (for example you created new post type 'album'), you can change the 'page' attribute to 'album' to show the meta box in the editing screen of 'album' only.

Below are custom fields. Each custom field has the following attributes:

  • name: The name of the custom field, it will be shown to user.
  • desc: A short description explaining what it is to the user.
  • id: the id of the field, prefixed by the $prefix. It will be used to store the custom field value
  • type: the input type: select, text, textarea, radio or checkbox
  • options: used to declare an array of options for a some type of input (select, radio)
  • std: the default value of the custom field.

Step 2. Add meta box to Edit Page

To add a meta box to edit page, we hook to admin_menu action as in the following code:

functions.php
add_action('admin_menu', 'mytheme_add_box');
// Add meta box
function mytheme_add_box() {
    global $meta_box;
    add_meta_box($meta_box['id'], $meta_box['title'], 'mytheme_show_box', $meta_box['page'], $meta_box['context'], $meta_box['priority']);
}

The function is used to add a meta box to edit page is add_meta_box. This function has 6 parameters:

add_meta_box($id, $title, $callback, $page, $context, $priority);

Each parameter has the same meaning as the meta box's attribute (I've explained it before), except the $callback parameter. The $callback parameter is the name of callback function, used to display HTML code of custom fields. In our situation, this function is mytheme_show_box.

Step 3. Show meta box

We need to implement the callback function mytheme_show_box to show HTML code of all custom fields. The function looks like:

functions.php
// Callback function to show fields in meta box
function mytheme_show_box() {
    global $meta_box, $post;
    // Use nonce for verification
    echo '<input type="hidden" name="mytheme_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
    echo '<table class="form-table">';
    foreach ($meta_box['fields'] as $field) {
        // get current post meta data
        $meta = get_post_meta($post->ID, $field['id'], true);
        echo '<tr>',
                '<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>',
                '<td>';
        switch ($field['type']) {
            case 'text':
                echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:97%" />', '<br />', $field['desc'];
                break;
            case 'textarea':
                echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="4" style="width:97%">', $meta ? $meta : $field['std'], '</textarea>', '<br />', $field['desc'];
                break;
            case 'select':
                echo '<select name="', $field['id'], '" id="', $field['id'], '">';
                foreach ($field['options'] as $option) {
                    echo '<option ', $meta == $option ? ' selected="selected"' : '', '>', $option, '</option>';
                }
                echo '</select>';
                break;
            case 'radio':
                foreach ($field['options'] as $option) {
                    echo '<input type="radio" name="', $field['id'], '" value="', $option['value'], '"', $meta == $option['value'] ? ' checked="checked"' : '', ' />', $option['name'];
                }
                break;
            case 'checkbox':
                echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' />';
                break;
        }
        echo     '</td><td>',
            '</td></tr>';
    }
    echo '</table>';
}

It is a large function, isn't it? But it's not very hard to understand.

In the very first of the function, we create a hidden field to store a nonce number. It's required to verify this came from the our screen and with proper authorization:

echo '<input type="hidden" name="mytheme_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';

And then we display all custom fields in a table. Using the PHP foreach loop, each field is displayed based on its type. Before displaying the custom field's value for select, radio and checkbox input types, we need to check the "saved" value (if it already exists) and compare to the default values. This is done via the line code last:

The HTML code of each custom fields is just input fields with some attributes like id, name, value, etc.

After this is done, we'll get the meta box on Editing Page like this:

Step 4. Save meta data when post is edited

To save the data of custom fields, we need to hook to save_post action:

functions.php
add_action('save_post', 'mytheme_save_data');
// Save data from meta box
function mytheme_save_data($post_id) {
    global $meta_box;
    // verify nonce
    if (!wp_verify_nonce($_POST['mytheme_meta_box_nonce'], basename(__FILE__))) {
        return $post_id;
    }
    // check autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $post_id;
    }
    // check permissions
    if ('page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_id)) {
            return $post_id;
        }
    } elseif (!current_user_can('edit_post', $post_id)) {
        return $post_id;
    }
    foreach ($meta_box['fields'] as $field) {
        $old = get_post_meta($post_id, $field['id'], true);
        $new = $_POST[$field['id']];
        if ($new && $new != $old) {
            update_post_meta($post_id, $field['id'], $new);
        } elseif ('' == $new && $old) {
            delete_post_meta($post_id, $field['id'], $old);
        }
    }
}

In the beginning of the function, we check the nonce to make sure that the data is come from edit post with proper authorization.

And then, we check the autosave feature. We don't want to save the data automatically via autosave feature. We want to save the data only when use clicked on the button Save (or Publish). If you really want to save the data via autosave feature, you can delete these lines (don't worry, they don't affect to the rest of code).

// check autosave if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; }

The last check is the user capability. We just check if user can edit post or page.

After all of verifications, we use the foreach loop to walk through every custom fields. If the custom fields is not in the database or it is changed, we update it (note: the update_post_meta also adds post meta when the meta is not present in database). If the custom fields is empty, we delete it from database.

When the post is edited or published, we can check the keys and values of custom fields as in the following screenshot (click to enlarge):

As you can see, that works!

Enjoy meta box script for WordPress

Using custom meta box is a great way to make custom fields more friendly to users. It helps us much to add extra information to a post. I hope this tutorial is helpful for you to easier implement a custom meta box in WordPress. I have made a file with all necessary code that you can include in your functions.php file. All you need to change (to fit your requirements) is only the prefix and meta box declaration at the very top of code.

page/post.php
// get current post meta data
$meta = get_post_meta($post->ID, $field['id'], true);
//$meta = get_post_meta($post->ID, 'dbt_text', true);
echo $meta;

Shortcodes

If you're unfamiliar with the concept of a BBCode, and by extension, shortcode, this is how the simplest version looks:

  • [my-gallery]
  • [button]Content[/button]
  • [link to="www.example.com"]Example+[/link]

Replacing Strings

functions.php
function signOffText() {  
    return 'Thank you so much for reading! And remember to subscribe to our RSS feed. ';  
} 
add_shortcode('signoff', 'signOffText');

That should do it. Just type [signoff] into your editor and WordPress will dynamically replace the text as needed.

page/post.php
<?php echo do_shortcode( '[signoff]' ) ?>

Wrapping Content

Next up, we're going to take a look at another variation: wrapping some content with some markup.

functions.php
function quote( $atts, $content = null ) {  
    return '<div class="right text">"'.$content.'"</div>';  
}
add_shortcode("quote", "quote");
[quote]Some text[/quote]

Adding Attributes

function link($atts, $content = null) {  
    extract(shortcode_atts(array(  
        "to" => 'http://example.com'  
    ), $atts));  
    return '<a href="'.$to.'">'.$content.'</a>';  
}
add_shortcode("link", "link");
[link to="www.example.com"]example+[/link]

Kicking Everything Up a Notch

functions.php
add_action('init', 'add_button');
// Create Our Initialization Function
function add_button() {  
   if ( current_user_can('edit_posts') &&  current_user_can('edit_pages') )  
   {  
     add_filter('mce_external_plugins', 'add_plugin');  
     add_filter('mce_buttons', 'register_button');  
   }  
}
// Register Our Button
function register_button($buttons) {  
   array_push($buttons, "quote");  
   return $buttons;  
}
// Register Our TinyMCE Plugin
function add_plugin($plugin_array) {  
   $plugin_array['quote'] = get_bloginfo('template_url').'/js/customcodes.js';  
   return $plugin_array;  
}
customcodes.js
(function() {  
    tinymce.create('tinymce.plugins.quote', {  
        init : function(ed, url) {  
            ed.addButton('quote', {  
                title : 'Add a Quote',  
                image : url+'/image.png',  
                onclick : function() {  
                     ed.selection.setContent('[quote]' + ed.selection.getContent() + '[/quote]');  
  
                }  
            });  
        },  
        createControl : function(n, cm) {  
            return null;  
        },  
    });  
    tinymce.PluginManager.add('quote', tinymce.plugins.quote);  
})();

Create the Callback Function - Display Recent Posts

functions.php
// CREATE THE CALLBACK FUNCTION
function recent_posts_function() {
   query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => 1));
   if (have_posts()) :
      while (have_posts()) : the_post();
         $return_string = '<a href="'.get_permalink().'">'.get_the_title().'</a>';
      endwhile;
   endif;
   wp_reset_query();
   return $return_string;
}
// REGISTER THE SHORTCODE
function register_shortcodes(){
   add_shortcode('recent-posts', 'recent_posts_function');
}
// HOOK INTO WORDPRESS
add_action( 'init', 'register_shortcodes');
page.php/single.php <?php echo do_shortcode( '[recent-posts]' ) ?>

Shortcode Parameters

 

WordPress Widget – Exclude some categories

<?php
class limited_catagories_list_widget extends WP_Widget {
function limited_catagories_list_widget(){
    $widget_ops = array( 'classname' => 'Selective categories',
    'description' => 'Show a list of Categories, option to exclude categories' );
    $control_ops = array( 'id_base' => 'some-cats-widget' );
    $this->WP_Widget( 'some-cats-widget', 'Selective Catagories',
    $widget_ops, $control_ops );
}

function form ( $instance){
    $defaults = array( 'title' => 'Catagories', 'cats' => '' );
    $instance = wp_parse_args( (array) $instance, $defaults );
    ?>
    <p>
            <label for="<?php echo $this->get_field_id( 'title' ); ?>">Title:</label>
            <input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" style="width:100%;" />
    </p>
    <p>
            <label for="<?php echo $this->get_field_id( 'cats' ); ?>">Categories to exclude(comma separated list of Category IDs): </label>
            <input id="<?php echo $this->get_field_id( 'cats' ); ?>" name="<?php echo $this->get_field_name( 'cats' ); ?>" value="<?php echo $instance['cats']; ?>" style="width:100%;" />
    </p>
    <?php
}

function update($new_instance, $old_instance) {
    $instance = $old_instance;
    $instance['title'] = strip_tags( $new_instance['title'] );
    $instance['cats'] = strip_tags( $new_instance['cats'] );
    return $instance;
}

function widget($args, $instance){
    extract( $args );
    $title = apply_filters('widget_title', $instance['title'] );
    $cats = $instance['cats'];
    echo $before_widget;
    if ( $title )
            echo $before_title . $title . $after_title;
    echo "<ul>";
    wp_list_categories("exclude=$cats&title_li=");
    echo "</ul>";
    echo $after_widget;
}

}

function register_jorbin_widget(){
    register_widget('limited_catagories_list_widget');
}
 
add_action('widgets_init', 'register_jorbin_widget');
?>

Localization

This theme is ready for localization via .po/.mo files, and works with the WPML plugin.

If you are not familiar with translating Wordpress themes, I recommend reading this article: http://codex.wordpress.org/Translating_WordPress

Change the language

  1. Check the values of your wp-config, the language of this file must match to your translation;
  2. Find the folder languages of the theme
  3. Duplicate default.po
  4. Rename your copy of default.po example: fr_FR.po for France, en_EN.po for English, he_HE.po for hebraic, and so on.
  5. Download POEdit
  6. Open your file with the POEdit software
  7. Translate your file
  8. In File click on Preferences and tick Automatically generate mo
  9. Save your file
  10. Send the new .mo and .po via FTP to your server in the folder languages of the theme

Disable WordPress Plugin Updates

# 2.3 to 2.7:
add_action( 'admin_menu', create_function( '$a', "remove_action( 'load-plugins.php', 'wp_update_plugins' );") );
	# Why use the admin_menu hook? It's the only one available between the above hook being added and being applied
add_action( 'admin_init', create_function( '$a', "remove_action( 'admin_init', 'wp_update_plugins' );"), 2 );
add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_update_plugins' );"), 2 );
add_filter( 'pre_option_update_plugins', create_function( '$a', "return null;" ) );

# 2.8 to 3.0:
remove_action( 'load-plugins.php', 'wp_update_plugins' );
remove_action( 'load-update.php', 'wp_update_plugins' );
remove_action( 'admin_init', '_maybe_update_plugins' );
remove_action( 'wp_update_plugins', 'wp_update_plugins' );
add_filter( 'pre_transient_update_plugins', create_function( '$a', "return null;" ) );

# 3.0:
remove_action( 'load-update-core.php', 'wp_update_plugins' );
add_filter( 'pre_site_transient_update_plugins', create_function( '$a', "return null;" ) );

Disable WordPress Core Updates

# 2.3 to 2.7:
add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );

# 2.8 to 3.0:
remove_action( 'wp_version_check', 'wp_version_check' );
remove_action( 'admin_init', '_maybe_update_core' );
add_filter( 'pre_transient_update_core', create_function( '$a', "return null;" ) );

# 3.0:
add_filter( 'pre_site_transient_update_core', create_function( '$a', "return null;" ) );

Disable or limit Post revisions using wp-config.php

To disable Post revisions simply open wp-config.php (file is located in root of WordPress installation) in you text editor, add this

wp-config.php
define( 'WP_POST_REVISIONS', false );

If you want to specify a maximum number of revisions, change false to an integer/number (e.g., 3 or 5).

define( 'WP_POST_REVISIONS', 3 );

Security Keys

In Version 2.6, three (3) security keys, AUTH_KEY, SECURE_AUTH_KEY, and LOGGED_IN_KEY, were added to ensure better encryption of information stored in the user's cookies. (These collectively replaced a single key introduced in Version 2.5.) In Version 2.7 a fourth key, NONCE_KEY, was added to this group. When each key was added, corresponding salts were added: AUTH_SALT, SECURE_AUTH_SALT, LOGGED_IN_SALT, and NONCE_SALT.

You don't have to remember the keys, just make them long, random and complicated -- or better yet, use the the online generator. You can change these at any point in time to invalidate all existing cookies. This does mean that all users will have to login again.

wp-config.php define('AUTH_KEY', '~ *;dlre$|dhf,l_AH!7.>k-La,meXKc?_u3}Sl|#U<?@1vGxjF0=cx>ge[PI8nn'); define('SECURE_AUTH_KEY', 'XCg|4+7<o|/L/!8(=nm|f=rzV5Mx_>[xZu7kSb3R#_?>[BTQ+V(ZQ3my{ocE7W+O'); define('LOGGED_IN_KEY', ';+s<gLtZq*pl` 1c2l&Sx-w{=yJYtW7$%+vk4-8w0E/{m49{P%;|8[P{[{uXtA*F'); define('NONCE_KEY', 'Nvmq6|9;4a|cHmHum+?el:4cpZB7=[O.ABMR4|M)^T{=NWt0`8<(Wy>@7.Q e,xx'); define('AUTH_SALT', 'tI!B27~P|E5E=irQP),LPN~loBZT/.&4AJG|D(#Cw~MId^fs`N0zc|W-]UVPeTNs'); define('SECURE_AUTH_SALT', 'Gx(b|h,CN+~P5gH|4%I}DD?[+R,[f?VT~~v--f+a?!;-`iE=M83f_vm5oR&ML3Os'); define('LOGGED_IN_SALT', 'c)`{_=J1Q!mt{ ${Su#GcgEoQMk-Ml6+%tF^#QX4)#ZD <}dPk3336-hWLkdO-Xp'); define('NONCE_SALT', '!X;ZIp!$@GhgH<kWRMZX#P1~_x|G,dKo61Ef42wwQ~?O@LslD&^q&XxlTce2A>E1');

Shot Content

functions.php
<?php
// Short Content
function short_content($num) {
	$limit = $num+1;
	$content= get_the_content();
	$content = strip_tags($content); // remove all tags
	//$content= preg_replace('/<img[^>]+./',"",$content); // remove img
	//$content = preg_replace ('/<[^>]*>/', ' ', $content); // HTML tags
	$content = str_split($content);
	$length = count($content);
	if ($length>=$num) {
	$content = array_slice( $content, 0, $num);
	$content = implode("",$content)."...";
	echo '<p>'.$content.'</p>';
	}
	else { 
		$content= get_the_content();
		$content = strip_tags($content); // remove all tags
		echo '<p>'.$content.'</p>';
	}
}
?>

Shot Title

functions.php
<?php
// Short Title
function short_title($num) {
	$limit = $num+1;
	$content = get_the_title();
	$content = strip_tags($content); // remove all tags
	//$content= preg_replace('/<img[^>]+./',"",$content); // remove img
	//$content = preg_replace ('/<[^>]*>/', ' ', $content); // HTML tags
	$content = str_split($content);
	$length = count($content);
	if ($length>=$num) {
	$content = array_slice( $content, 0, $num);
	$content = implode("",$content)."...";
	echo $content;
	}
	else { 
		$content= get_the_title();
		$content = strip_tags($content); // remove all tags
		echo '<p>'.$content.'</p>';
	}
}
?>
page.php/single.php
<?php short_title(101); ?>

Add Custom field in backend (Meta Box)

functions.php
add_action('add_meta_boxes', 'c3m_sponsor_meta');
function c3m_sponsor_meta() {
    add_meta_box('c3m_meta', 'Year of Publications', 'c3m_sponsor_url_meta', 'post', 'side', 'high');
}

function c3m_sponsor_url_meta($post) {
    $c3m_sponsor_url = get_post_meta($post->ID, '_c3m_sponsor_url', true);
    echo 'Please enter the year of publication';
    ?>
      
    <input type = "text" name = "c3m_sponsor_url" value = "<?php echo esc_attr( $c3m_sponsor_url ); ?>" / >
    <?php
}

add_action('save_post', 'c3m_save_project_meta');
function c3m_save_project_meta($post_ID) {
    global $post;
    if ($post->post_type == "post") {
        if (isset($_POST)) {
            update_post_meta($post_ID, '_c3m_sponsor_url', strip_tags($_POST['c3m_sponsor_url']));
        }
    }
}

Adding Extra Fields to the WordPress User Profile

functions.php
<?php
add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );

function extra_user_profile_fields( $user ) { ?>
<h3><?php _e("Extra profile information", "blank"); ?></h3>

<table class="form-table">
<tr>
<th><label for="address"><?php _e("Address"); ?></label></th>
<td>
<input type="text" name="address" id="address" value="<?php echo esc_attr( get_the_author_meta( 'address', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e("Please enter your address."); ?></span>
</td>
</tr>
<tr>
<th><label for="city"><?php _e("City"); ?></label></th>
<td>
<input type="text" name="city" id="city" value="<?php echo esc_attr( get_the_author_meta( 'city', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e("Please enter your city."); ?></span>
</td>
</tr>
<tr>
<th><label for="province"><?php _e("Province"); ?></label></th>
<td>
<input type="text" name="province" id="province" value="<?php echo esc_attr( get_the_author_meta( 'province', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e("Please enter your province."); ?></span>
</td>
</tr>
<tr>
<th><label for="postalcode"><?php _e("Postal Code"); ?></label></th>
<td>
<input type="text" name="postalcode" id="postalcode" value="<?php echo esc_attr( get_the_author_meta( 'postalcode', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e("Please enter your postal code."); ?></span>
</td>
</tr>
</table>
<?php }

add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );

function save_extra_user_profile_fields( $user_id ) {

if ( !current_user_can( 'edit_user', $user_id ) ) { return false; }

update_user_meta( $user_id, 'address', $_POST['address'] );
update_user_meta( $user_id, 'city', $_POST['city'] );
update_user_meta( $user_id, 'province', $_POST['province'] );
update_user_meta( $user_id, 'postalcode', $_POST['postalcode'] );
}
?>

Limit Search Results For Specific Post Types

functions.php
function searchfilter($query) {

    if ($query->is_search && !is_admin() ) {
        $query->set('post_type',array('post','page'));
    }

return $query;
}

add_filter('pre_get_posts','searchfilter');

Add custom fields under wp general settings

functions.php
add_filter('admin_init', 'my_general_settings_register_fields');
 
function my_general_settings_register_fields()
{
    register_setting('general', 'my_field', 'esc_attr');
    add_settings_field('my_field', '<label for="my_field">'.__('My Field' , 'my_field' ).'</label>' , 'my_general_settings_fields_html', 'general');
}
 
function my_general_settings_fields_html()
{
    $value = get_option( 'my_field', '' );
    echo '<input type="text" id="my_field" name="my_field" value="' . $value . '" />';
}
page.php/single.php
<?php echo get_option('my_field'); ?>

Remove Admin Menu page

<?php
function remove_menus(){

  remove_menu_page( 'index.php' );                  //Dashboard
  remove_menu_page( 'edit.php' );                   //Posts
  remove_menu_page( 'upload.php' );                 //Media
  remove_menu_page( 'edit.php?post_type=page' );    //Pages
  remove_menu_page( 'edit-comments.php' );          //Comments
  remove_menu_page( 'themes.php' );                 //Appearance
  remove_menu_page( 'plugins.php' );                //Plugins
  remove_menu_page( 'users.php' );                  //Users
  remove_menu_page( 'tools.php' );                  //Tools
  remove_menu_page( 'options-general.php' );        //Settings
  
  //remove_submenu_page( 'themes.php', 'customize.php' );
  //global $submenu;
  //unset($submenu['themes.php'][6]); // Customize

  remove_submenu_page( 'options-general.php', 'options-writing.php' );
  remove_submenu_page( 'options-general.php', 'options-reading.php' );
  remove_submenu_page( 'options-general.php', 'options-discussion.php' );
  
}
add_action( 'admin_menu', 'remove_menus' );
?>

Add Admin CSS

add_action('admin_head', 'my_custom_fonts');

function my_custom_fonts() {
  echo '<style>
    body, td, textarea, input, select {
      font-family: "Lucida Grande";
      font-size: 12px;
    } 
  </style>';
}

Rename a user role name via hook

function change_role_name() {
    global $wp_roles;

    if ( ! isset( $wp_roles ) )
        $wp_roles = new WP_Roles();

    //You can list all currently available roles like this...
    //$roles = $wp_roles->get_names();
    //print_r($roles);

    //You can replace "editor" with any other role "administrator", "author", "contributor" or "subscriber"...
    $wp_roles->roles['editor']['name'] = 'Owner';
    $wp_roles->role_names['editor'] = 'Owner';           
}
add_action('init', 'change_role_name');

Remove roles

<?php remove_role( 'subscriber' ); ?>

Redirect non admins to homepage

function custom_login_redirect( $redirect_to, $request, $user  ) {
	return ( is_array( $user->roles ) && in_array( 'administrator', $user->roles ) ) ? admin_url() : site_url();
} // end soi_login_redirect
add_filter( 'login_redirect', 'custom_login_redirect', 10, 3 );

Disable Admin Dashboard Access Except Admin

add_action('admin_init', 'no_mo_dashboard');
function no_mo_dashboard() {
  if (!current_user_can('manage_options') && $_SERVER['DOING_AJAX'] != '/wp-admin/admin-ajax.php') {
  wp_redirect(home_url()); exit;
  }
}

Hide Page Editor Based on Page ID

function remove_editor() {
    if (isset($_GET['post'])) {
        $id = $_GET['post'];
		$template = get_post_meta($id, '_wp_page_template', true);
		
		if( '161' == $_GET['post'] && 'edit' == $_GET['action'] )
		remove_post_type_support( 'page', 'editor' );
        

        /*if($template == 'template_name.php'){ 
            remove_post_type_support( 'page', 'editor' );
        }*/
    }
}
add_action('init', 'remove_editor');

Formatting Date and Time

Certain WordPress tag functions are used to display or return date and time information; the_date() and the_time() are examples of this. Some of these functions accept a parameter called a format string that allows you to determine how the date is going to be displayed. The format string is a template in which various parts of the date are combined (using "format characters") to generate a date in the format specified.

For example, the format string:

l, F j, Y

creates a date that look like this:

Friday, September 24, 2004

Here is what each format character in the string above represents:

  • l = Full name for day of the week (lower-case L).
  • F = Full name for the month.
  • j = The day of the month.
  • Y = The year in 4 digits. (lower-case y gives the year's last 2 digits)
(Commas are read literally.)

WordPress is written in the programming language PHP. The date formatting functions in WordPress use PHP's built-in date formatting functions. You can use the table of date format characters on the PHP website as a reference for building date format strings for use in WordPress. Here is a table of some of the more useful items found there:

Day of Month
d Numeric, with leading zeros 01–31
j Numeric, without leading zeros 1–31
S The English suffix for the day of the month st, nd or th in the 1st, 2nd or 15th.
Weekday
l Full name  (lowercase 'L') Sunday – Saturday
D Three letter name Mon – Sun
Month
m Numeric, with leading zeros 01–12
n Numeric, without leading zeros 1–12
F Textual full January – December
M Textual three letters Jan - Dec
Year
Y Numeric, 4 digits Eg., 1999, 2003
y Numeric, 2 digits Eg., 99, 03
Time
a Lowercase am, pm
A Uppercase AM, PM
g Hour, 12-hour, without leading zeros 1–12
h Hour, 12-hour, with leading zeros 01–12
G Hour, 24-hour, without leading zeros 0-23
H Hour, 24-hour, with leading zeros 00-23
i Minutes, with leading zeros 00-59
s Seconds, with leading zeros 00-59
T Timezone abbreviation Eg., EST, MDT ...
Full Date/Time
c ISO 8601 2004-02-12T15:19:21+00:00
r RFC 2822 Thu, 21 Dec 2000 16:01:07 +0200

Examples

Here are some examples of date format and result output.

  • F j, Y g:i a - November 6, 2010 12:50 am
  • F j, Y - November 6, 2010
  • F, Y - November, 2010
  • g:i a - 12:50 am
  • g:i:s a - 12:50:48 am
  • l, F jS, Y - Saturday, November 6th, 2010
  • M j, Y @ G:i - Nov 6, 2010 @ 0:50
  • Y/m/d \a\t g:i A - 2010/11/06 at 12:50 AM
  • Y/m/d \a\t g:ia - 2010/11/06 at 12:50am
  • Y/m/d g:i:s A - 2010/11/06 12:50:48 AM
  • Y/m/d - 2010/11/06

Combined with the_time() template tag, the code below in the template file:

This entry was posted on <?php the_time('l, F jS, Y') ?> and is filed under <?php the_category(', ') ?>.

will be shown on your site as following:

This entry was posted on Friday, September 24th, 2004 and is filed under WordPress and WordPress Tips.

Localization

To localize dates, use the date_i18n() function.

You can probably safely localize these date format strings with the __(), _e(), etc. functions (demonstrated with get_the_date(__(…))):

Escaping

You can escape custom characters using the \letter format. For example you would escape the text at with \a\t.

Adding Categories And Post Tags Boxes For Custom Post Type "Demo"

Categories and Post Tags boxes are built-in meta boxes that have been already registered in WordPress. We can use them not only for default posts or pages but also for custom post types as well in WordPress. And this can be done easily with argument taxonomies of register_post_type() function when registering new custom post type.

In this example, I'll register a new post type called "demo" with categories and post tags boxes:

 

 

add_action('init', 'demo_register_post_type');
 
function demo_register_post_type() {
    register_post_type('demo', array(
        'labels' => array(
            'name' => 'Demos',
            'singular_name' => 'Demo',
            'add_new' => 'Add new demo',
            'edit_item' => 'Edit demo',
            'new_item' => 'New demo',
            'view_item' => 'View demo',
            'search_items' => 'Search demos',
            'not_found' => 'No demos found',
            'not_found_in_trash' => 'No demos found in Trash'
        ),
        'public' => true,
        'supports' => array(
            'title',
            'excerpt'
        ),
        'taxonomies' => array('category', 'post_tag') // this is IMPORTANT
    ));
}

 

The taxonomies is an array of registered taxonomies that will be used with this post type. The taxonomy for categories is category and for post tags is post_tag. Both of them are automatically registered, and we can use them without re-defining.

Sometimes, your blog has registered a custom post type already, and you don't want to search in a bunch of code just to find out where the register_post_type() function to add a small line for categories and post tags boxes. To solve this problem, you can add them (categories and post tags boxes) later using register_taxonomy_for_object_type() function like this:

 

add_action('init', 'demo_add_default_boxes');
 
function demo_add_default_boxes() {
    register_taxonomy_for_object_type('category', 'demo');
    register_taxonomy_for_object_type('post_tag', 'demo');
}

 

Note that all these functions have to be called with init action hook. Otherwise, the custom post type is still registered, but no categories or post tags boxes.


Usefull Links

Online Tools 

 

 

 

Study 

 

Lorem Ipsum

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.


Custom Post Type

Display Custom Post Type Blog

<?php query_posts( 'post_type=blog&taxonomy=procategory&tag_ID=6' );
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <?php the_title() ;?>
    <a href="<?php echo get_permalink($post->ID); ?>">
    <h1><?php the_title(); ?></h1></a>
<?php endwhile; endif; ?>

Add Custom Post Type Blog

function my_custom_post_blog() {
	$labels = array(
		'name'               => _x( 'Blogs', 'post type general name' ),
		'singular_name'      => _x( 'Blog', 'post type singular name' ),
		'add_new'            => _x( 'Add New', 'book' ),
		'add_new_item'       => __( 'Add New Blog' ),
		'edit_item'          => __( 'Edit Blog' ),
		'new_item'           => __( 'New Blog' ),
		'all_items'          => __( 'All Blog' ),
		'view_item'          => __( 'View Blog' ),
		'search_items'       => __( 'Search Blog' ),
		'not_found'          => __( 'No Blog found' ),
		'not_found_in_trash' => __( 'No Blog found in the Trash' ), 
		'parent_item_colon'  => '',
		'menu_name'          => 'Blogs'
	);
	$args = array(
		'labels'        => $labels,
		'description'   => 'Holds our Blogs and Blog specific data',
		'public'        => true,
		'menu_position' => 5,
		'supports'      => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),
		'has_archive'   => true,
	);
	register_post_type( 'blog', $args );	
}
add_action( 'init', 'my_custom_post_blog' );
function my_updated_messages( $messages ) {
	global $post, $post_ID;
	$messages['blog'] = array(
		0 => '', 
		1 => sprintf( __('Blog updated. <a href="%s">View Blog</a>'), esc_url( get_permalink($post_ID) ) ),
		2 => __('Custom field updated.'),
		3 => __('Custom field deleted.'),
		4 => __('Blog updated.'),
		5 => isset($_GET['revision']) ? sprintf( __('Blog restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
		6 => sprintf( __('Blog published. <a href="%s">View Blog</a>'), esc_url( get_permalink($post_ID) ) ),
		7 => __('blog saved.'),
		8 => sprintf( __('Blog submitted. <a target="_blank" href="%s">Preview Blog</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
		9 => sprintf( __('Blog scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview Blog</a>'), date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
		10 => sprintf( __('Blog draft updated. <a target="_blank" href="%s">Preview Blog</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
	);
	return $messages;
}
add_filter( 'post_updated_messages', 'my_updated_messages' );
function my_contextual_help( $contextual_help, $screen_id, $screen ) { 
	if ( 'blog' == $screen->id ) {
		$contextual_help = '<h2>Blogs</h2>
		<p>Blogs show the details of the items that we sell on the website. You can see a list of them on this page in reverse chronological order - the latest one we added is first.</p> 
		<p>You can view/edit the details of each Blog by clicking on its name, or you can perform bulk actions using the dropdown menu and selecting multiple items.</p>';
	} elseif ( 'edit-blog' == $screen->id ) {
		$contextual_help = '<h2>Editing blogs</h2>
		<p>This page allows you to view/modify blog details. Please make sure to fill out the available boxes with the appropriate details (blog image, price, brand) and <strong>not</strong> add these details to the blog description.</p>';
	}
	return $contextual_help;
}
add_action( 'contextual_help', 'my_contextual_help', 10, 3 );
function my_taxonomies_blog() {
	$labels = array(
		'name'              => _x( 'Blog Categories', 'taxonomy general name' ),
		'singular_name'     => _x( 'Blog Category', 'taxonomy singular name' ),
		'search_items'      => __( 'Search Blog Categories' ),
		'all_items'         => __( 'All Blog Categories' ),
		'parent_item'       => __( 'Parent Blog Category' ),
		'parent_item_colon' => __( 'Parent Blog Category:' ),
		'edit_item'         => __( 'Edit Blog Category' ), 
		'update_item'       => __( 'Update Blog Category' ),
		'add_new_item'      => __( 'Add New Blog Category' ),
		'new_item_name'     => __( 'New Blog Category' ),
		'menu_name'         => __( 'Blog Categories' ),
	);
	$args = array(
		'labels' => $labels,
		'hierarchical' => true,
	);
	register_taxonomy( 'blog_category', 'blog', $args );
}
add_action( 'init', 'my_taxonomies_blog', 0 );
 

Add Custom Post Type Product

function my_custom_post_product() {
	$labels = array(
		'name'               => _x( 'Products', 'post type general name' ),
		'singular_name'      => _x( 'Product', 'post type singular name' ),
		'add_new'            => _x( 'Add New', 'book' ),
		'add_new_item'       => __( 'Add New product' ),
		'edit_item'          => __( 'Edit product' ),
		'new_item'           => __( 'New product' ),
		'all_items'          => __( 'All product' ),
		'view_item'          => __( 'View product' ),
		'search_items'       => __( 'Search product' ),
		'not_found'          => __( 'No product found' ),
		'not_found_in_trash' => __( 'No product found in the Trash' ), 
		'parent_item_colon'  => '',
		'menu_name'          => 'Products'
	);
	$args = array(
		'labels'        => $labels,
		'description'   => 'Holds our products and product specific data',
		'public'        => true,
		'menu_position' => 5,
		'supports'      => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),
		'has_archive'   => true,
	);
	register_post_type( 'product', $args );	
}
add_action( 'init', 'my_custom_post_product' );
function my_updated_messages( $messages ) {
	global $post, $post_ID;
	$messages['product'] = array(
		0 => '', 
		1 => sprintf( __('product updated. <a href="%s">View product</a>'), esc_url( get_permalink($post_ID) ) ),
		2 => __('Custom field updated.'),
		3 => __('Custom field deleted.'),
		4 => __('product updated.'),
		5 => isset($_GET['revision']) ? sprintf( __('product restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
		6 => sprintf( __('product published. <a href="%s">View product</a>'), esc_url( get_permalink($post_ID) ) ),
		7 => __('product saved.'),
		8 => sprintf( __('product submitted. <a target="_blank" href="%s">Preview product</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
		9 => sprintf( __('product scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview product</a>'), date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
		10 => sprintf( __('product draft updated. <a target="_blank" href="%s">Preview product</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
	);
	return $messages;
}
add_filter( 'post_updated_messages', 'my_updated_messages' );
function my_contextual_help( $contextual_help, $screen_id, $screen ) { 
	if ( 'product' == $screen->id ) {
		$contextual_help = '<h2>products</h2>
		<p>products show the details of the items that we sell on the website. You can see a list of them on this page in reverse chronological order - the latest one we added is first.</p> 
		<p>You can view/edit the details of each product by clicking on its name, or you can perform bulk actions using the dropdown menu and selecting multiple items.</p>';
	} elseif ( 'edit-product' == $screen->id ) {
		$contextual_help = '<h2>Editing products</h2>
		<p>This page allows you to view/modify product details. Please make sure to fill out the available boxes with the appropriate details (product image, price, brand) and <strong>not</strong> add these details to the product description.</p>';
	}
	return $contextual_help;
}
add_action( 'contextual_help', 'my_contextual_help', 10, 3 );
function my_taxonomies_product() {
	// Add new taxonomy, make it hierarchical (like categories)
	$labels = array(
		'name'              => _x( 'Product Category', 'taxonomy general name' ),
		'singular_name'     => _x( 'Product Category', 'taxonomy singular name' ),
		'search_items'      => __( 'Search Product Category' ),
		'all_items'         => __( 'All Product Category' ),
		'parent_item'       => __( 'Parent Product Category' ),
		'parent_item_colon' => __( 'Parent Product Category:' ),
		'edit_item'         => __( 'Edit Product Category' ),
		'update_item'       => __( 'Update Product Category' ),
		'add_new_item'      => __( 'Add New Product Category' ),
		'new_item_name'     => __( 'New Product Category Name' ),
		'menu_name'         => __( 'Product Category' ),
	);

	$args = array(
		'hierarchical'      => true,
		'labels'            => $labels,
		'show_ui'           => true,
		'show_admin_column' => true,
		'query_var'         => true,
		'rewrite'           => array( 'slug' => 'procategory' ),
	);

	register_taxonomy( 'procategory', array( 'product' ), $args );
	
	// Add new taxonomy, make it hierarchical (like categories)
	$labels = array(
		'name'              => _x( 'Brand Name', 'taxonomy general name' ),
		'singular_name'     => _x( 'Brand Name', 'taxonomy singular name' ),
		'search_items'      => __( 'Search Brand Name' ),
		'all_items'         => __( 'All Brand Name' ),
		'parent_item'       => __( 'Parent Brand Name' ),
		'parent_item_colon' => __( 'Parent Brand Name:' ),
		'edit_item'         => __( 'Edit Brand Name' ),
		'update_item'       => __( 'Update Brand Name' ),
		'add_new_item'      => __( 'Add New Brand Name' ),
		'new_item_name'     => __( 'New Brand Name' ),
		'menu_name'         => __( 'Brand Name' ),
	);

	$args = array(
		'hierarchical'      => true,
		'labels'            => $labels,
		'show_ui'           => true,
		'show_admin_column' => true,
		'query_var'         => true,
		'rewrite'           => array( 'slug' => 'probrand' ),
	);

	register_taxonomy( 'probrand', array( 'product' ), $args );

	// Add new taxonomy, NOT hierarchical (like tags)
	$labels = array(
		'name'                       => _x( 'Tags', 'taxonomy general name' ),
		'singular_name'              => _x( 'Tag', 'taxonomy singular name' ),
		'search_items'               => __( 'Search Tags' ),
		'popular_items'              => __( 'Popular Tags' ),
		'all_items'                  => __( 'All Tags' ),
		'parent_item'                => null,
		'parent_item_colon'          => null,
		'edit_item'                  => __( 'Edit Tag' ),
		'update_item'                => __( 'Update Tag' ),
		'add_new_item'               => __( 'Add New Tag' ),
		'new_item_name'              => __( 'New Tag Name' ),
		'separate_items_with_commas' => __( 'Separate Tag with commas' ),
		'add_or_remove_items'        => __( 'Add or remove Tags' ),
		'choose_from_most_used'      => __( 'Choose from the most used Tags' ),
		'not_found'                  => __( 'No Tags found.' ),
		'menu_name'                  => __( 'Tags' ),
	);

	$args = array(
		'hierarchical'          => false,
		'labels'                => $labels,
		'show_ui'               => true,
		'show_admin_column'     => true,
		'update_count_callback' => '_update_post_term_count',
		'query_var'             => true,
		'rewrite'               => array( 'slug' => 'protag' ),
	);

	register_taxonomy( 'protag', 'product', $args );
}
add_action( 'init', 'my_taxonomies_product', 0 );
 

Quick Register Custom Post Type

When register custom post type in WordPress, the most boring work is writing labels for menus and notifications. If your theme has several custom post types, that work will be repeated again and again. In this case, we can avoid duplication by creating a function that handle all the labels and other parameters automatically, and call it with minimum arguments when needed.

 

function rw_register_post_type( $post_type = '', $args = array() )
{
    if ( empty( $post_type ) )
        return;
    $singular = empty( $args['singular'] ) ? $post_type : $args['singular'];
    $singular = str_replace( '_', ' ', $singular );
    $singular = ucwords( $singular );
    $plural = empty( $args['plural'] ) ? "{$singular}s" : $args['plural'];
    $plural = ucwords( $plural );
    $plural_lower = strtolower( $plural );
    $args['labels'] = empty( $args['labels'] ) ? array() : $args['labels'];
    $args['labels'] = wp_parse_args( $args['labels'], array(
        'name'               => $plural,
        'singular_name'      => $singular,
        'add_new'            => __( 'Add New', 'your_textdomain' ),
        'add_new_item'       => sprintf( __( 'Add New %s', 'your_textdomain' ), $singular ),
        'edit_item'          => sprintf( __( 'Edit %s', 'your_textdomain' ), $singular ),
        'new_item'           => sprintf( __( 'New %s', 'your_textdomain' ), $singular ),
        'view_item'          => sprintf( __( 'View %s', 'your_textdomain' ), $singular ),
        'search_items'       => sprintf( __( 'Search %s', 'your_textdomain' ), $plural ),
        'not_found'          => sprintf( __( 'No %s found', 'your_textdomain' ), $plural_lower ),
        'not_found_in_trash' => sprintf( __( 'No %s found in Trash', 'your_textdomain' ), $plural_lower ),
        'parent_item_colon'  => null,
        'all_items'          => sprintf( __( 'All %s', 'your_textdomain' ), $plural ),
        'menu_name'          => $plural,
    ) );
    $args = wp_parse_args( $args, array(
        'public' => true,
    ) );
    register_post_type( $post_type, $args );
}

How to use

Simple example: NO arguments

rw_register_post_type( 'book' );
rw_register_post_type( 'movie' );

This will register custom post type book and create singular label Book as well as plural label Books and apply to menu items and notifications.

Different types of plural label

rw_register_post_type( 'company', array(
    'plural' => 'companies',
) );
rw_register_post_type( 'box', array(
    'plural' => 'boxes',
) );

The plural argument is used when you need to specified plural label, in case it's not auto generated by adding s to singular label.

Handle other arguments

rw_register_post_type( 'company', array(
    'hierarchy' => 'true',
    'public' => false,
) );

This function can handle all default WordPress arguments used by register_post_type function. All arguments are optional. By default it uses only public => true.

 

The Complete Guide To Custom Post Types

A custom post type is nothing more than a regular post with a different post_type value in the database. The post type of regular posts is post, pages use page, attachments use attachment and so on. You can now create your own to indicate the type of content created. You could create custom post types for books, movies, reviews, products and so on.


Category

Display Parent Category (root)

page.php/single.php
<?php
// Display root Category
$args = array(
	'type'                     => 'post',
	'child_of'                 => 0,
	'parent'                   => '',
	'orderby'                  => 'date',
	'order'                    => 'DESC',
	'hide_empty'               => 0,
	'hierarchical'             => 1,
	'exclude'                  => '',
	'include'                  => '',
	'number'                   => '',
	'taxonomy'                 => 'category',
	'pad_counts'               => false 

); 
$categories = get_categories($args);
foreach($category as $value)
{ 
if($value->category_parent == 0){
?>
    <?php echo $value->name; ?> <br/>
    <?php echo $value->description; ?><br/>
    <a href="<?php $category_link = get_category_link( $value->term_id ); echo $category_link; ?>">readmore</a>
<?php }}
// Display root Category
?>

Display sub Category

category.php
<?php
$args = array(
	'type'                     => 'post',
	'child_of'                 => $cat,
	'parent'                   => '',
	'orderby'                  => 'name',
	'order'                    => 'ASC',
	'hide_empty'               => 1,
	'hierarchical'             => 1,
	'exclude'                  => '',
	'include'                  => '',
	'number'                   => '',
	'taxonomy'                 => 'category',
	'pad_counts'               => false 

); 
$category = get_categories($args);
if ( $category ) :
?>
<!--Display sub Category-->
<ul class="looping grid">
<?php 
foreach($category as $value)
{ 
?>
        <li class="looping-category loop">
			<?php echo $value->name; ?> <br/>
			<?php echo $value->description; ?><br/>
          	<?php $category_link = get_category_link( $value->term_id ); ?><br/>
          	<a href="<?php echo $category_link; ?>">readmore</a>
        </li>
<?php } ?>
</ul>
<!--Display sub Category--> 
<?php else : ?>
<?php single_cat_title( );  ?>
<!--Display posts in Category--> 
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2><?php the_title() ;?></h2>
<?php the_post_thumbnail(); ?>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p>Sorry, no posts to list</p>
<?php endif; ?>
<!--Display posts in Category--> 
<?php endif; ?> 

Add Extra field in Category Edit Page

function.php
<?php
// Add term page
function pippin_taxonomy_add_new_meta_field() {
	// this will add the custom meta field to the add new term page
	?>
	<div class="form-field">
		<label for="term_meta[custom_term_meta]"><?php _e( 'Example meta field', 'pippin' ); ?></label>
		<input type="text" name="term_meta[custom_term_meta]" id="term_meta[custom_term_meta]" value="">
		<p class="description"><?php _e( 'Enter a value for this field','pippin' ); ?></p>
	</div>
<?php
}
add_action( 'category_add_form_fields', 'pippin_taxonomy_add_new_meta_field', 10, 2 );
// Edit term page
function pippin_taxonomy_edit_meta_field($term) {
 
	// put the term ID into a variable
	$t_id = $term->term_id;
 
	// retrieve the existing value(s) for this meta field. This returns an array
	$term_meta = get_option( "taxonomy_$t_id" ); ?>
	<tr class="form-field">
	<th scope="row" valign="top"><label for="term_meta[custom_term_meta]"><?php _e( 'Menu Color Class', 'pippin' ); ?></label></th>
		<td>
			<input type="text" name="term_meta[custom_term_meta]" id="term_meta[custom_term_meta]" value="<?php echo esc_attr( $term_meta['custom_term_meta'] ) ? esc_attr( $term_meta['custom_term_meta'] ) : ''; ?>" style="width:100px !important;">
			<p class="description"><?php _e( 'pink, blue, violet, yellow','pippin' ); ?></p>
		</td>
	</tr>
<?php
}
add_action( 'category_edit_form_fields', 'pippin_taxonomy_edit_meta_field', 10, 2 );
// Save extra taxonomy fields callback function.
function save_taxonomy_custom_meta( $term_id ) {
	if ( isset( $_POST['term_meta'] ) ) {
		$t_id = $term_id;
		$term_meta = get_option( "taxonomy_$t_id" );
		$cat_keys = array_keys( $_POST['term_meta'] );
		foreach ( $cat_keys as $key ) {
			if ( isset ( $_POST['term_meta'][$key] ) ) {
				$term_meta[$key] = $_POST['term_meta'][$key];
			}
		}
		// Save the option array.
		update_option( "taxonomy_$t_id", $term_meta );
	}
}  
add_action( 'edited_category', 'save_taxonomy_custom_meta', 10, 2 );  
add_action( 'create_category', 'save_taxonomy_custom_meta', 10, 2 );

The first parameter is what determines the taxonomy that this field gets added to. It uses this format: {$taxonomy_name}_add_form_fields. So if you wanted to add the field to your "genres" taxonomy, you would use:

add_action( 'genres_add_form_fields', 'pippin_taxonomy_add_new_meta_field', 10, 2 ); add_action( 'edited_genres', 'save_taxonomy_custom_meta', 10, 2 ); add_action( 'create_genres', 'save_taxonomy_custom_meta', 10, 2 ); page.php/single.php
$t_id = $term->term_id;
$term_meta = get_option( "taxonomy_$t_id" );
<?php echo esc_attr( $term_meta['custom_term_meta'] ) ? esc_attr( $term_meta['custom_term_meta'] ) : ''; ?>

Taxonomy

Display Parent Taxonomy (root)

page.php/single.php
<?php
// Display root Taxonomy
$args = array(
	'type'                     => 'post',
	'child_of'                 => 0,
	'parent'                   => '',
	'orderby'                  => 'date',
	'order'                    => 'DESC',
	'hide_empty'               => 0,
	'hierarchical'             => 1,
	'exclude'                  => '',
	'include'                  => '',
	'number'                   => '',
	'taxonomy'                 => 'taxonomy',
	'pad_counts'               => false 

); 
$categories = get_categories($args);
foreach($category as $value)
{ 
if($value->category_parent == 0){
?>
    <?php echo $value->name; ?> <br/>
    <?php echo $value->description; ?><br/>
    <a href="<?php $category_link = get_category_link( $value->term_id ); echo $category_link; ?>">readmore</a>
<?php }}
// Display root Taxonomy
?>

Display sub Taxonomy

taxonomy.php
<?php
$queried_object = get_queried_object();  
$term_id = $queried_object->term_id;
$args = array(
	'type'                     => 'posttype',
	'child_of'                 => $term_id,
	'parent'                   => '',
	'orderby'                  => 'name',
	'order'                    => 'ASC',
	'hide_empty'               => 1,
	'hierarchical'             => 1,
	'exclude'                  => '',
	'include'                  => '',
	'number'                   => '',
	'taxonomy'                 => 'taxonomy',
	'pad_counts'               => false 

); 
$category = get_categories($args);
if ( $category ) :
?>
<!--Display sub Category-->
<ul class="looping grid">
<?php 
foreach($category as $value)
{ 
?>
        <li class="looping-category loop">
        <?php echo $value->name; ?> <br/>
        <?php echo $value->description; ?><br/>
        <?php $category_link = get_term_link( $value , 'taxonomy' ); ?><br/>
        <a href="<?php echo $category_link; ?>">readmore</a>
        </li>
<?php } ?>
</ul>
<!--Display sub Category--> 
<?php else : ?>
<?php single_cat_title( );  ?>
<!--Display posts in Category--> 
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<a href="<?php echo get_permalink($post->ID); ?>"><h2><?php the_title() ;?></h2></a>
<?php the_post_thumbnail(); ?>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p>Sorry, no posts to list</p>
<?php endif; ?>
<!--Display posts in Category--> 
<?php endif; ?> 

Snippers

Display Terms inside loop

taxonomy.php
<?php
$terms = wp_get_post_terms(get_the_ID(), 'team_group', array('orderby' => 'id', 'order' => 'ASC', "fields" => "names"));
if ( !empty( $terms ) && !is_wp_error( $terms ) ) {
	$count = count($terms);
    $i=0;
    $term_list = '';
    foreach ($terms as $term) {
        $i++;
        $term_list .= $term;
        if ($count != $i) {
            $term_list .= ' / ';
        }
        else {
            $term_list .= '';
        }
    }
    echo $term_list;
}
?>