Month: November 2015

Google map display with dynamic address

Set dynamic google map in our website using this script.

$yourAddress="ujala circle ahmedabad";

Add this code your contact page or your required page.

Advertisements

Standard Media Queries For Responsive Website

standard media queries for css responsive mobile layout for all screen. all types of mobile, tablets and desktop.

@media(min-width:320px) and (max-width:479px)
{
}
@media(min-width:480px) and (max-width:567px)
{
}
@media(min-width:568px) and (max-width:684px)
{
}
@media(min-width:685px) and (max-width:767px)
{
}
@media(min-width:768px) and (max-width:991px)
{
}
@media(min-width:992px) and (max-width:1024px)
{
}
@media(min-width:1023px) and (max-width:1200px)
{
}

Change the Select Box List with CSS

Change the Default Select Box List with CSS in all browser. Select Drop Down style for Firefox,Google Chrome, Safari and other Browser.

Well the reality is that you shouldn’t complain to the designer because little things like this makes you push yourself a little bit harder and not rely on default stylings just because.

put this code in style sheet.

.dropdown {
border: 0;
-webkit-appearance: none;            /*Removes default chrome and safari style*/
-moz-appearance: none;             /* Removes Default Firefox style*/
background: url('dropdown_style.png') no-repeat;          /*Adds background-image*/
background-position: 82px 7px;           /*Position of the background-image*/
width: 100px;            /    *Width of select dropdown to give space for arrow image*/
text-indent: 0.01px;          /* Removes default arrow from firefox*/
text-overflow: "";               /*Removes default arrow from firefox*/
}

WordPress How to use bootstrap navigation menu

This code you can used easily Bootstrap drop-down menu.

Under the ‘menu’ item in the array below you will need to change ‘main_nav’ to whatever name you decide to give your menu bar in the WordPress Admin Dashboard. That is the only location you need to change ‘main_nav’ as all the other references to ‘main_nav’ can remain.


/**
/* Class Name: wp_bootstrap_navwalker
/* Create new file as wp_bootstrap_navwalker.php or add this code in functions.php
/* 
/* if create file so Register Custom Navigation Walker.	 as like require_once('wp_bootstrap_navwalker.php');
/*/
class wp_bootstrap_navwalker extends Walker_Nav_Menu {	
	public function start_lvl( &$output, $depth = 0, $args = array() ) {
		$indent = str_repeat( "\t", $depth );
		$output .= "\n$indent<ul role=\"menu\" class=\" dropdown-menu\">\n";
	}

	public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
		$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
		/**
		 * Dividers, Headers or Disabled
		 * =============================
		 * a 0 if the strings are equal.
		 */
		if ( strcasecmp( $item->attr_title, 'divider' ) == 0 && $depth === 1 ) {
			$output .= $indent . '<li role="presentation" class="divider">';
		} else if ( strcasecmp( $item->title, 'divider') == 0 && $depth === 1 ) {
			$output .= $indent . '<li role="presentation" class="divider">';
		} else if ( strcasecmp( $item->attr_title, 'dropdown-header') == 0 && $depth === 1 ) {
			$output .= $indent . '<li role="presentation" class="dropdown-header">' . esc_attr( $item->title );
		} else if ( strcasecmp($item->attr_title, 'disabled' ) == 0 ) {
			$output .= $indent . '<li role="presentation" class="disabled"><a href="#">' . esc_attr( $item->title ) . '</a>';
		} else {
			$class_names = $value = '';
			$classes = empty( $item->classes ) ? array() : (array) $item->classes;
			$classes[] = 'menu-item-' . $item->ID;
			$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
			if ( $args->has_children )
				$class_names .= ' dropdown';
			if ( in_array( 'current-menu-item', $classes ) )
				$class_names .= ' active';
			$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
			$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
			$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
			$output .= $indent . '<li' . $id . $value . $class_names .'>';
			$atts = array();
			$atts['title']  = ! empty( $item->title )	? $item->title	: '';
			$atts['target'] = ! empty( $item->target )	? $item->target	: '';
			$atts['rel']    = ! empty( $item->xfn )		? $item->xfn	: '';
			// If item has_children add atts to a.
			if ( $args->has_children && $depth === 0 ) {
				$atts['href']   		= '#';
				$atts['data-toggle']	= 'dropdown';
				$atts['class']			= 'dropdown-toggle';
				$atts['aria-haspopup']	= 'true';
			} else {
				$atts['href'] = ! empty( $item->url ) ? $item->url : '';
			}
			$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args );
			$attributes = '';
			foreach ( $atts as $attr => $value ) {
				if ( ! empty( $value ) ) {
					$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
					$attributes .= ' ' . $attr . '="' . $value . '"';
				}
			}
			$item_output = $args->before;
			/*
			 * Glyphicons
			 * ===========			
			 */
			if ( ! empty( $item->attr_title ) )
				$item_output .= '<a'. $attributes .'><span class="glyphicon ' . esc_attr( $item->attr_title ) . '"></span>&nbsp;';
			else
				$item_output .= '<a'. $attributes .'>';
			$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
			$item_output .= ( $args->has_children && 0 === $depth ) ? ' <span class="caret"></span></a>' : '</a>';
			$item_output .= $args->after;
			$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
		}
	}
	
	public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
        if ( ! $element )
            return;
        $id_field = $this->db_fields['id'];
        // Display this element.
        if ( is_object( $args[0] ) )
           $args[0]->has_children = ! empty( $children_elements[ $element->$id_field ] );
        parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
    }
	/**
	 * Menu Fallback
	 * =============	 
	 *
	 */
	public static function fallback( $args ) {
		if ( current_user_can( 'manage_options' ) ) {
			extract( $args );
			$fb_output = null;
			if ( $container ) {
				$fb_output = '<' . $container;
				if ( $container_id )
					$fb_output .= ' id="' . $container_id . '"';
				if ( $container_class )
					$fb_output .= ' class="' . $container_class . '"';
				$fb_output .= '>';
			}
			$fb_output .= '<ul';
			if ( $menu_id )
				$fb_output .= ' id="' . $menu_id . '"';
			if ( $menu_class )
				$fb_output .= ' class="' . $menu_class . '"';
			$fb_output .= '>';
			$fb_output .= '<li><a href="' . admin_url( 'nav-menus.php' ) . '">Add a menu</a></li>';
			$fb_output .= '</ul>';
			if ( $container )
				$fb_output .= '</' . $container . '>';
			echo $fb_output;
		}
	}
}

Register Walker in functions.php

/************/
/* Register Custom Navigation Walker
/************/
require_once('wp_bootstrap_navwalker.php');

Call Walker in header.php

/************/
/* Usage in your heder file.
/************/

 wp_nav_menu( array(
                'menu'              => 'primary',
                'theme_location'    => 'primary',
                'depth'             => 2,
                'container'         => 'div',
                'container_class'   => 'collapse navbar-collapse',
        'container_id'      => 'bs-example-navbar-collapse-1',
                'menu_class'        => 'nav navbar-nav',
                'fallback_cb'       => 'wp_bootstrap_navwalker::fallback',
                'walker'            => new wp_bootstrap_navwalker())
            );

Custom meta box for post and pages

A custom meta (or write) box is incredibly simple in theory. It allows you to add a custom piece of data to a post or page in WordPress.

meta box main used  plugin developers to add meta boxes to the administrative interface.

Put This Code in functions.php

 add_action( 'add_meta_boxes', 'meta_box_keywords' );
function meta_box_keywords()
{
$post_page = array( 'post', 'page' );
foreach ( $post_page as $post_pages ) {
add_meta_box( 'meta_box_keyword_id', 'Product Option', 'akey_word', $post_pages, 'normal', 'high' );
}
} 

Change read more excerpt wordpress

when you work on wordpress and change the default excerpt then you add this code in your functions.php and it’w work 100% as you like.

function new_excerpt_more( $more ) {
return '<div><a href="'. get_permalink( get_the_ID() ) . '">' . __('Read More...', 'euasia') . '</a></div>';
}
add_filter('excerpt_more', 'new_excerpt_more');

User avatar upload frontend

Put this code functions.php file then you can change user profile image.

function custom_avatar_field( $user ) { ?>
<?php  wp_enqueue_media(); ?>

jQuery(document).ready(function($){
var custom_uploader;
$(‘#upload_image_button’).click(function(e) {

e.preventDefault();

//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}

//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: ‘Choose Image’,
button: {
text: ‘Choose Image’
},
multiple: false
});

//When a file is selected, grab the URL and set it as the text field’s value
custom_uploader.on(‘select’, function() {
attachment = custom_uploader.state().get(‘selection’).first().toJSON();
$(‘#upload_image’).val(attachment.id);
$(‘#image’).attr(‘src’, attachment.url);
});

//Open the uploader dialog
custom_uploader.open();

});

});

<h3>Ozone Avatar</h3>
<table>
<tr>
<td><label for=”be_custom_avatar”>Avatar Image:</label></td>
<td><label for=”upload_image”>
<input id=”upload_image” type=”hidden” size=”36″ name=”ad_image” value=”<?php echo get_user_meta($user->ID,’be_custom_avatar’,true)?>” />
<input id=”upload_image_button” type=”button” value=”Upload Image” />
</label></td>
<td><img src=”<?php echo wp_get_attachment_url(get_user_meta($user->ID,’be_custom_avatar’,true));?>” id=”image”  style=”height:100px;”/></td>
</tr>
</table>
<?php
}
add_action( ‘show_user_profile’, ‘custom_avatar_field’ );
add_action( ‘edit_user_profile’, ‘custom_avatar_field’ );

/**
* Save Ozone Avatar Field
*@author Ommune Team
* @link http://www.ommune.com/
* @param int $user_id
*/
function save_custom_avatar_field( $user_id ) {
if ( !current_user_can( ‘edit_user’, $user_id ) ) { return false; }
update_user_meta( $user_id, ‘be_custom_avatar’, $_POST[‘ad_image’] );
}
add_action( ‘personal_options_update’, ‘save_custom_avatar_field’ );
add_action( ‘edit_user_profile_update’, ‘save_custom_avatar_field’ );

/**
* Use Ozone Avatar if Provided
* @author Ommune Team
* @link http://www.ommune.com/
*
*/
function wp_gravatar_filter($avatar, $id_or_email, $size, $default, $alt) {
$custom_avatar =  get_the_author_meta(‘be_custom_avatar’,$id_or_email);
if ($custom_avatar)
$return = get_wp_user_avatar_image($id_or_email, $size, $default, $alt);
elseif ($avatar)
$return = $avatar;
else
$return = ‘<img src=”‘.$default.'” width=”‘.$size.'” height=”‘.$size.'” alt=”‘.$alt.'” />’;
return $return;
}
add_filter(‘get_avatar’, ‘wp_gravatar_filter’, 10, 5);

// Find avatar, show get_avatar if empty
function get_wp_user_avatar_image($id_or_email=””, $size=’96’, $align=””, $alt=””, $email=’unknown@gravatar.com’){
global $avatar_default, $blog_id, $post, $wpdb, $_wp_additional_image_sizes;
// Checks if comment
if(is_object($id_or_email)){
// Checks if comment author is registered user by user ID
if($id_or_email->user_id != 0){
$email = $id_or_email->user_id;
// Checks that comment author isn’t anonymous
} elseif(!empty($id_or_email->comment_author_email)){
// Checks if comment author is registered user by e-mail address
$user = get_user_by(’email’, $id_or_email->comment_author_email);
// Get registered user info from profile, otherwise e-mail address should be value
$email = !empty($user) ? $user->ID : $id_or_email->comment_author_email;
}
$alt = $id_or_email->comment_author;
} else {
if(!empty($id_or_email)){
// Find user by ID or e-mail address
$user = is_numeric($id_or_email) ? get_user_by(‘id’, $id_or_email) : get_user_by(’email’, $id_or_email);
} else {
// Find author’s name if id_or_email is empty
$author_name = get_query_var(‘author_name’);
if(is_author()){
// On author page, get user by page slug
$user = get_user_by(‘slug’, $author_name);
} else {
// On post, get user by author meta
$user_id = get_the_author_meta(‘ID’);
$user = get_user_by(‘id’, $user_id);
}
}
// Set user’s ID and name
if(!empty($user)){
$email = $user->ID;
$alt = $user->display_name;
}
}
// Checks if user has avatar
$wpua_meta = get_the_author_meta($wpdb->get_blog_prefix($blog_id).’user_avatar’, $email);
$wpua_meta = get_the_author_meta(‘be_custom_avatar’,$email);

// Add alignment class
$alignclass = !empty($align) && ($align == ‘left’ || $align == ‘right’ || $align == ‘center’) ? ‘ align’.$align : ‘ alignnone’;
// User has avatar, bypass get_avatar
if(!empty($wpua_meta)){
// Numeric size use size array
$get_size = is_numeric($size) ? array($size,$size) : $size;
// Get image src
$wpua_image = wp_get_attachment_image_src($wpua_meta, $get_size);
$dimensions = is_numeric($size) ? ‘ width=”‘.$wpua_image[1].'” height=”‘.$wpua_image[2].'”‘ : “”;
// Construct the img tag

$avatar = ‘<img src=”‘.$wpua_image[0].'”‘.$dimensions.’ alt=”‘.$alt.'” />’;
} else {
// Get numeric sizes for non-numeric sizes based on media options
if(!function_exists(‘get_intermediate_image_sizes’)){
require_once(ABSPATH.’wp-admin/includes/media.php’);
}
// Check for custom image sizes
$all_sizes = array_merge(get_intermediate_image_sizes(), array(‘original’));
if(in_array($size, $all_sizes)){
if(in_array($size, array(‘original’, ‘large’, ‘medium’, ‘thumbnail’))){
$get_size = ($size == ‘original’) ? get_option(‘large_size_w’) : get_option($size.’_size_w’);
} else {
$get_size = $_wp_additional_image_sizes[$size][‘width’];
}
} else {
// Numeric sizes leave as-is
$get_size = $size;
}
// User with no avatar uses get_avatar
$avatar = get_avatar($email, $get_size, $default=””, $alt=””);
// Remove width and height for non-numeric sizes
if(in_array($size, array(‘original’, ‘large’, ‘medium’, ‘thumbnail’))){
$avatar = preg_replace(‘/(width|height)=”d*”s/’, “”, $avatar);
$avatar = preg_replace(“/(width|height)=’d*’s/”, “”, $avatar);
}
$str_replacemes = array(‘wp-user-avatar ‘, ‘wp-user-avatar-‘.$get_size.’ ‘, ‘wp-user-avatar-‘.$size.’ ‘, ‘avatar-‘.$get_size, ‘photo’);
$str_replacements = array(“”, “”, “”, ‘avatar-‘.$size, ‘wp-user-avatar wp-user-avatar-‘.$size.$alignclass.’ photo’);
$avatar = str_replace($str_replacemes, $str_replacements, $avatar);
}
return $avatar;
}

create table in wordpress using functions.php

By using this code you can create table in sql and if you want to insert data than use wp insert…

<?php
global $wpdb;

$appointment_table_name = $wpdb->prefix . “book_an_appointment”;
if($wpdb->get_var(“show tables like ‘$appointment_table_name'”) != $appointment_table_name) {

$sql = “CREATE TABLE ” . $appointment_table_name . ” (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL,
phone VARCHAR(25) NOT NULL,
date VARCHAR(25) NOT NULL,
time VARCHAR(25) NOT NULL,
comment VARCHAR(1500) NOT NULL,
UNIQUE KEY id (id)
);”;

require_once(ABSPATH . ‘wp-admin/includes/upgrade.php’);
dbDelta($sql);

}
?>

Custom post type with sorting and filtering


/**
* Plugin Name: Custom Post Type Man
* Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates
* Description: A brief description of the plugin.
* Version: The plugin's version number. Example: 1.0.0
* Author: Name of the plugin author
* Author URI: http://URI_Of_The_Plugin_Author
* Text Domain: customposttyoe
* Domain Path: Optional. Plugin's relative directory path to .mo files. Example: /locale/
* Network: Optional. Whether the plugin can only be activated network wide. Example: true
* License: A short license name. Example: GPL2
*/
add_action('init', 'create_portfolio_post_type');

function create_portfolio_post_type() {
$args = array(
'description' => 'Portfolio Post Type',
'show_ui' => true,
'menu_position' => 4,
'exclude_from_search' => true,
'labels' => array(
'name' => 'Portfolios',
'singular_name' => 'Portfolios',
'add_new' => 'Add New Portfolio',
'add_new_item' => 'Add New Portfolio',
'edit' => 'Edit Portfolios',
'edit_item' => 'Edit Portfolio',
'new-item' => 'New Portfolio',
'view' => 'View Portfolios',
'view_item' => 'View Portfolio',
'search_items' => 'Search Portfolios',
'not_found' => 'No Portfolios Found',
'not_found_in_trash' => 'No Portfolios Found in Trash',
'parent' => 'Parent Portfolio'
),
'public' => true,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => true,
'supports' => array('title', 'editor', 'thumbnail', 'comments', 'tags')
);
register_post_type('portfolio', $args);
}

/* ====================================================
Register Custom Taxonomies
====================================================== */

add_action('init', 'register_portfolio_taxonomy');

function register_portfolio_taxonomy() {
register_taxonomy('portfolio_category', 'portfolio', array(
'labels' => array(
'name' => 'Portfolio Categories',
'singular_name' => 'Portfolio Categories',
'search_items' => 'Search Portfolio Categories',
'popular_items' => 'Popular Portfolio Categories',
'all_items' => 'All Portfolio Categories',
'parent_item' => 'Parent Portfolio Category',
'parent_item_colon' => 'Parent Portfolio Category:',
'edit_item' => 'Edit Portfolio Category',
'update_item' => 'Update Portfolio Category',
'add_new_item' => 'Add New Portfolio Category',
'new_item_name' => 'New Portfolio Category',
),
'hierarchical' => true,
'show_ui' => true,
'show_tagcloud' => true,
'rewrite' => false,
'public' => true
)
);
}

/* ====================================================
Register Custom Tags
====================================================== */
add_action('init', 'register_portfolio_tags');

function register_portfolio_tags() {
register_taxonomy('portfolio_tag', 'portfolio', array(
'hierarchical' => false,
'labels' => array(
'name' => _x('Portfolio Tags', 'taxonomy general name', 'customposttyoe'),
'singular_name' => _x('Portfolio Tag', 'taxonomy singular name', 'customposttyoe'),
'search_items' => __('Search Tags', 'customposttyoe'),
'popular_items' => __('Popular Tags', 'customposttyoe'),
'all_items' => __('All Tags', 'customposttyoe'),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __('Edit Portfolio Tag', 'customposttyoe'),
'update_item' => __('Update Portfolio Tag', 'customposttyoe'),
'add_new_item' => __('Add New Portfolio Tag', 'customposttyoe'),
'new_item_name' => __('New Portfolio Tag Name', 'customposttyoe'),
'separate_items_with_commas' => __('Separate Portfolio Tag with commas', 'customposttyoe'),
'add_or_remove_items' => __('Add or remove portfolio Tag', 'customposttyoe'),
'choose_from_most_used' => __('Choose from the most used portfolio Tag', 'customposttyoe')
),
'show_ui' => true,
'query_var' => true,
'rewrite' => false,
));
}

/* ====================================================
Add extra columns
====================================================== */

add_filter("manage_edit-portfolio_columns", "portfolio_edit_columns");

function portfolio_edit_columns($columns) {

$columns = array(
"cb" => "<input type='checkbox' />",
"title" => __("Portfolio"),
"photo" => __("Image"),
"portfolio_category" => __("Portfolio Category"),
"portfolio_tag" => __("Portfolio Tag"),
"portfolio_rating" => __("Portfolio Rating"),
"date" => __("Date")
);
return $columns;
}

add_action("manage_portfolio_posts_custom_column", "portfolio_custom_columns");

function portfolio_custom_columns($column) {
global $post;
switch ($column) {
case "photo":
if (has_post_thumbnail())
the_post_thumbnail(array(50, 50));
break;
case "portfolio_category":
echo get_the_term_list($post->ID, 'portfolio_category', '', ', ', '');
break;
case "portfolio_tag":
echo get_the_term_list($post->ID, 'portfolio_tag', '', ', ', '');
break;
case "portfolio_rating":
echo intval(get_post_meta($post->ID, 'portfolio_rating', true));
break;
}
}

/* ====================================================
Add filter on categories.
====================================================== */
if (isset($_GET['post_type'])) {
$post_type = $_GET['post_type'];
} else {
$post_type = '';
}

if ($post_type == 'portfolio') {
add_action('restrict_manage_posts', 'portfolio_filter_list');
add_filter('parse_query', 'perform_filtering');

add_action('restrict_manage_posts', 'portfolio_filter_tags');
}
/*
* Filter in select box category
*/
function portfolio_filter_list() {
global $typenow, $wp_query;
if ($typenow == 'portfolio') {
wp_dropdown_categories(array(
'show_option_all' => 'Show All Portfolio Category',
'taxonomy' => 'portfolio_category',
'name' => 'portfolio_category',
'orderby' => 'name',
'selected' => ( isset($wp_query->query['portfolio_category']) ? $wp_query->query['portfolio_category'] : '' ),
'hierarchical' => false,
'depth' => 3,
'show_count' => false,
'hide_empty' => true,
));
}
}
/*
* Filter in select box tags
*/
function portfolio_filter_tags() {
global $typenow, $wp_query;
if ($typenow == 'portfolio') {
wp_dropdown_categories(array(
'show_option_all' => 'Show All Portfolio Tags',
'taxonomy' => 'portfolio_tag',
'name' => 'portfolio_tag',
'orderby' => 'name',
'selected' => ( isset($wp_query->query['portfolio_tag']) ? $wp_query->query['portfolio_tag'] : '' ),
'hierarchical' => false,
'depth' => 3,
'show_count' => false,
'hide_empty' => true,
));
}
}
/*
* Filter in select box and fill data.
*/
function perform_filtering($query) {
$qv = &$query->query_vars;
if (isset($qv['portfolio_category'])) {
if (( $qv['portfolio_category'] ) && is_numeric($qv['portfolio_category'])) {
$term = get_term_by('id', $qv['portfolio_category'], 'portfolio_category');
$qv['portfolio_category'] = $term->slug;
}
}

if (isset($qv['portfolio_tag'])) {
if (( $qv['portfolio_tag'] ) && is_numeric($qv['portfolio_tag'])) {
$term = get_term_by('id', $qv['portfolio_tag'], 'portfolio_tag');
$qv['portfolio_tag'] = $term->slug;
}
}
}

/* ====================================================
Add Sortable columns
====================================================== */
add_filter('manage_edit-portfolio_sortable_columns', 'portfolio_sortable_columns');

function portfolio_sortable_columns($columns) {

$columns['portfolio_category'] = 'portfolio_category';
$columns['portfolio_tag'] = 'portfolio_tag';
$columns['portfolio_rating'] = 'portfolio_rating';
return $columns;
}
/* ====================================================
Add Sortable columns on Portfolio Rating
====================================================== */
add_action('pre_get_posts', 'portfolio_category_orderby');
function portfolio_category_orderby($query) {
if (!is_admin())
return;
$orderby = $query->get('orderby');

print_r($orderby);//die;
if ('portfolio_category' == $orderby) {
$query->set('taxonomy', 'portfolio_category');
}
}
/* ====================================================
Add Sortable columns on Portfolio Rating
====================================================== */
add_action('pre_get_posts', 'portfolio_rating_orderby');
function portfolio_rating_orderby($query) {
if (!is_admin())
return;
$orderby = $query->get('orderby');
if ('portfolio_rating' == $orderby) {
$query->set('meta_key', 'portfolio_rating');
$query->set('orderby', 'meta_value_num');
}
}

/* ====================================================
* Function creates post duplicate as a draft and redirects then to the edit post screen
====================================================== */
add_filter('post_row_actions', 'rd_duplicate_post_link', 10, 2);

function rd_duplicate_post_as_draft() {
global $wpdb;
if (!( isset($_GET['post']) || isset($_POST['post']) || ( isset($_REQUEST['action']) && 'rd_duplicate_post_as_draft' == $_REQUEST['action'] ) )) {
wp_die('No post to duplicate has been supplied!');
}

/*
* get the original post id
*/
$post_id = (isset($_GET['post']) ? $_GET['post'] : $_POST['post']);
/*
* and all the original post data then
*/
$post = get_post($post_id);

/*
* if you don't want current user to be the new post author,
* then change next couple of lines to this: $new_post_author = $post->post_author;
*/
$current_user = wp_get_current_user();
$new_post_author = $current_user->ID;

/*
* if post data exists, create the post duplicate
*/
if (isset($post) && $post != null) {

/*
* new post data array
*/
$args = array(
'comment_status' => $post->comment_status,
'ping_status' => $post->ping_status,
'post_author' => $new_post_author,
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt,
'post_name' => $post->post_name,
'post_parent' => $post->post_parent,
'post_password' => $post->post_password,
'post_status' => 'draft',
'post_title' => $post->post_title,
'post_type' => $post->post_type,
'to_ping' => $post->to_ping,
'menu_order' => $post->menu_order
);

/*
* insert the post by wp_insert_post() function
*/
$new_post_id = wp_insert_post($args);

/*
* get all current post terms ad set them to the new post draft
*/
$taxonomies = get_object_taxonomies($post->post_type); // returns array of taxonomy names for post type, ex array("category", "post_tag");
foreach ($taxonomies as $taxonomy) {
$post_terms = wp_get_object_terms($post_id, $taxonomy, array('fields' => 'slugs'));
wp_set_object_terms($new_post_id, $post_terms, $taxonomy, false);
}

/*
* duplicate all post meta
*/
$post_meta_infos = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id=$post_id");
if (count($post_meta_infos) != 0) {
$sql_query = "INSERT INTO $wpdb->postmeta (post_id, meta_key, meta_value) ";
foreach ($post_meta_infos as $meta_info) {
$meta_key = $meta_info->meta_key;
$meta_value = addslashes($meta_info->meta_value);
$sql_query_sel[] = "SELECT $new_post_id, '$meta_key', '$meta_value'";
}
$sql_query.= implode(" UNION ALL ", $sql_query_sel);
$wpdb->query($sql_query);
}
/*
* finally, redirect to the edit post screen for the new draft
*/
wp_redirect(admin_url('post.php?action=edit&post=' . $new_post_id));
exit;
} else {
wp_die('Post creation failed, could not find original post: ' . $post_id);
}
}

add_action('admin_action_rd_duplicate_post_as_draft', 'rd_duplicate_post_as_draft');

/* ====================================================
* Add the duplicate link to action list for post_row_actions
* ====================================================== */

function rd_duplicate_post_link($actions, $post) {
if ($post->post_type == "portfolio"):
$actions['duplicate'] = '<a href="admin.php?action=rd_duplicate_post_as_draft&amp;post=' . $post->ID . '" title="Duplicate this item" rel="permalink">Duplicate</a>';
endif;
return $actions;
}

/* ====================================================
* Add the custom meta box
* ====================================================== */

add_action('admin_init', 'my_admin');

function my_admin() {
add_meta_box('portfolio_review_meta_box', 'Portfolio Review Details', 'display_portfolio_review_meta_box', 'portfolio', 'normal', 'high'
);
}

function display_portfolio_review_meta_box($portfolio_review) {
// Retrieve current name of the Director and Portfolio Rating based on review ID
$portfolio_director = esc_html(get_post_meta($portfolio_review->ID, 'portfolio_director', true));
$portfolio_rating = intval(get_post_meta($portfolio_review->ID, 'portfolio_rating', true));
?>
<table>
<tr>
<td style="width: 100%">Portfolio Director</td>
<td><input type="text" size="80" name="portfolio_review_director_name" value="<?php echo $portfolio_director; ?>" /></td>
</tr>
<tr>
<td style="width: 150px">Portfolio Rating</td>
<td>
<select style="width: 100px" name="portfolio_review_rating">
<?php
// Generate all items of drop-down list
for ($rating = 5; $rating >= 1; $rating --) {
?>
<option value="<?php echo $rating; ?>" <?php echo selected($rating, $portfolio_rating); ?>>
<?php echo $rating; ?> stars <?php } ?>
</select>
</td>
</tr>
</table>
<?php
}

add_action('save_post', 'add_portfolio_review_fields', 10, 2);

function add_portfolio_review_fields($portfolio_review_id, $portfolio_review) {
// Check post type for portfolio reviews
if ($portfolio_review->post_type == 'portfolio') {
// Store data in post meta table if present in post data
if (isset($_POST['portfolio_review_director_name']) && $_POST['portfolio_review_director_name'] != '') {
update_post_meta($portfolio_review_id, 'portfolio_director', $_POST['portfolio_review_director_name']);
}
if (isset($_POST['portfolio_review_rating']) && $_POST['portfolio_review_rating'] != '') {
update_post_meta($portfolio_review_id, 'portfolio_rating', $_POST['portfolio_review_rating']);
}
}
}