Pages

Thursday, December 19, 2013

Add custom class to wordpress navigation

Please write below code in functions.php

add_filter('nav_menu_css_class', 'current_type_nav_class', 10, 2);
function current_type_nav_class($classes, $item) {
// Get post_type for this post
// Go to Menus and add a menu class named: {custom-post-type}-menu-item
// This adds a current_page_parent class to the parent menu item
if( in_array( $post_type.'-menu-item', $classes ) )
array_push($classes, 'current_page_parent');

return $classes;

}

Generate re-write rules for custom post type - wordpress

Please write below code in functions.php

function wp_rewrite_rules($wp_rewrite) {
    $rules = wp_generate_date_archives('CUSTOM_POST_TYPE_SLUG', $wp_rewrite);
    $wp_rewrite->rules = $rules + $wp_rewrite->rules;
    return $wp_rewrite;
}

add_action('generate_rewrite_rules', 'wp_rewrite_rules');
function wp_generate_date_archives($postslug, $wp_rewrite) {
    $rules = array();

    $post_type = get_post_type_object($postslug);
    $slug_archive = $post_type->has_archive;
    if ($slug_archive === false) return $rules;
    if ($slug_archive === true) {
        $slug_archive = $post_type->name;
    }

    $dates = array(
        array(
            'rule' => "([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})",
            'vars' => array('year', 'monthnum', 'day')),
        array(
            'rule' => "([0-9]{4})/([0-9]{1,2})",
            'vars' => array('year', 'monthnum')),
        array(
            'rule' => "([0-9]{4})",
            'vars' => array('year')),
        array(
            'rule' => "([^/]+)",
            'vars' => array('name'))
        );

    foreach ($dates as $data) {
        $query = 'index.php?post_type='.$postslug;
        $rule = $slug_archive.'/'.$data['rule'];

        $i = 1;
        foreach ($data['vars'] as $var) {
            $query.= '&'.$var.'='.$wp_rewrite->preg_index($i);
            $i++;
        }
        $rules[$rule."/?$"] = $query;
        $rules[$rule."/feed/(feed|rdf|rss|rss2|atom)/?$"] = $query."&feed=".$wp_rewrite->preg_index($i);
        $rules[$rule."/(feed|rdf|rss|rss2|atom)/?$"] = $query."&feed=".$wp_rewrite->preg_index($i);
        $rules[$rule."/page/([0-9]{1,})/?$"] = $query."&paged=".$wp_rewrite->preg_index($i);
    }
    return $rules;
}

Create yearly archive listing for custom post type + wordpress - solved


Please write below code in functions.php

function get_cpt_archives( $cpt, $echo = false ) // $cpt = custom post type slug
{
    global $wpdb;
    $sql = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_type = %s AND post_status = 'publish' GROUP BY YEAR(wp_posts.post_date), MONTH(wp_posts.post_date) ORDER BY wp_posts.post_date DESC", $cpt);
    $results = $wpdb->get_results($sql);

    if ( $results )
    {
        $archive = array();
        foreach ($results as $r)
        {
            $year = date('Y', strtotime( $r->post_date ) );
            $month = date('F', strtotime( $r->post_date ) );
            $month_num = date('m', strtotime( $r->post_date ) );
            $link = get_bloginfo('siteurl') . '/corporate/' . $cpt . '/' . $year . '/' . $month_num;
            $this_archive = array( 'month' => $month, 'year' => $year, 'link' => $link );
            array_push( $archive, $this_archive );
        }

        if( !$echo )
            return $archive;
        foreach( $archive as $a )
        {
            echo '<li><a href="' . $a['link'] . '">' . $a['month'] . ' ' . $a['year'] . '</a></li>';
        }
    }
    return false;
}

In sidebar page you have to write below function:

get_cpt_archives('Custom Post Type Slug');

Wordpress child page redirect to custom template - solved

I want to change template for all child page of news page.

For this I have write below code in functions.php

function switch_corporate_child_service_page_template() {
    global $post;
    if (is_page())
{
// Checks if page is parent, if yes, return
if ($post->post_parent == 0)
return true;
else if ($post->post_parent == '20064') // "20064" is "News" page id.
{
$template = TEMPLATEPATH . "/page-corporate_services.php";
if (file_exists($template)) {
load_template($template);
exit;
}
}
}
}


add_action('template_redirect','switch_corporate_child_service_page_template');

Custom post type redirect to home page + wordpress

Please write below code in functions.php

add_action("template_redirect", 'template_redirect_news');

function template_redirect_news()
{
global $wp;
$custom_post_types = array("faq" , "testimonial"); // please write here which custom post type you want to redirect to home page

if (in_array($wp->query_vars["post_type"], $custom_post_types))
{
if($wp->query_vars["name"]):
wp_redirect(get_site_url());
die();
endif;
}
}


Tuesday, December 10, 2013

How to change Custom Taxonomy Links?


function custom_term_link_url($content) {
    $current_path = 'live-topics';
    $new_path = 'live/topic';
    $content = str_replace($current_path, $new_path, $content);
    return $content;
}
add_filter('term_link', 'custom_term_link_url');

function add_query_vars_for_live_topics($aVars) {
    $aVars[] = "live-topics";    // represents the name of the product category as shown in the URL
    return $aVars;
}
add_filter('query_vars', 'add_query_vars_for_live_topics');

function add_rewrite_rules_live_topics($aRules) {
    $aNewRules = array('live/topic/([^/]+)/?$' => 'index.php?live-topics=$matches[1]');
    $aRules = $aNewRules + $aRules;
    return $aRules;
}
add_filter('rewrite_rules_array', 'add_rewrite_rules_live_topics');

Monday, October 21, 2013

United Kingdom postal code validation - PHP [resolved]

<?php

function check_uk_postcode($string){
// Start config
$valid_value = 'true';
$invalid_value = 'false';
$exceptions = array('BS981TL', 'BX11LT', 'BX21LB', 'BX32BB', 'BX55AT', 'CF101BH', 'CF991NA', 'DE993GG', 'DH981BT', 'DH991NS', 'E161XL', 'E202AQ', 'E202BB', 'E202ST', 'E203BS', 'E203EL', 'E203ET', 'E203HB', 'E203HY', 'E981SN', 'E981ST', 'E981TT', 'EC2N2DB', 'EC4Y0HQ', 'EH991SP', 'G581SB', 'GIR0AA', 'IV212LR', 'L304GB', 'LS981FD', 'N19GU', 'N811ER', 'NG801EH', 'NG801LH', 'NG801RH', 'NG801TH', 'SE18UJ', 'SN381NW', 'SW1A0AA', 'SW1A0PW', 'SW1A1AA', 'SW1A2AA', 'SW1P3EU', 'SW1W0DT', 'TW89GS', 'W1A1AA', 'W1D4FA', 'W1N4DJ');
// Add Overseas territories ?
array_push($exceptions, 'AI-2640', 'ASCN1ZZ', 'STHL1ZZ', 'TDCU1ZZ', 'BBND1ZZ', 'BIQQ1ZZ', 'FIQQ1ZZ', 'GX111AA', 'PCRN1ZZ', 'SIQQ1ZZ', 'TKCA1ZZ');
// End config


$string = strtoupper(preg_replace('/\s/', '', $string)); // Remove the spaces and convert to uppercase.
$exceptions = array_flip($exceptions);
if(isset($exceptions[$string])){return $valid_value;} // Check for true exception
$length = strlen($string);
if($length < 5 || $length > 7){return $invalid_value;} // Check for false length
$letters = array_flip(range('A', 'Z')); // An array of letters as keys
$numbers = array_flip(range(0, 9)); // An array of numbers as keys

switch($length){
case 7:
if(!isset($letters[$string[0]], $letters[$string[1]], $numbers[$string[2]], $numbers[$string[4]], $letters[$string[5]], $letters[$string[6]])){break;}
if(isset($letters[$string[3]]) || isset($numbers[$string[3]])){
return $valid_value;
}
break;
case 6:
if(!isset($letters[$string[0]], $numbers[$string[3]], $letters[$string[4]], $letters[$string[5]])){break;}
if(isset($letters[$string[1]], $numbers[$string[2]]) || isset($numbers[$string[1]], $letters[$string[2]]) || isset($numbers[$string[1]], $numbers[$string[2]])){
return $valid_value;
}
break;
case 5:
if(isset($letters[$string[0]], $numbers[$string[1]], $numbers[$string[2]], $letters[$string[3]], $letters[$string[4]])){
return $valid_value;
}
break;
}

return $invalid_value;
}
?>

Friday, October 4, 2013

Category Widget show empty records/categories - Wordpress




add_filter( 'widget_categories_args', 'pctheme_widget_cat_args' );
function pctheme_widget_cat_args($cat_args) {
    $cat_args['hide_empty'] = 0; 
    return $cat_args;
}

Wednesday, September 25, 2013

wp_get_archives highlight current archive



function pc_theme_get_archives_link ( $link_html ) {
    global $wp;
    static $current_url;
    if ( empty( $current_url ) ) {
        $current_url = add_query_arg( $_SERVER['QUERY_STRING'], '', home_url( $wp->request ) );
    }
    if ( stristr( $link_html, $current_url ) !== false ) {
        $link_html = preg_replace( '/(<[^\s>]+)/', '\1 class="active"', $link_html, 1 );
    }
    return $link_html;
}
add_filter('get_archives_link', 'pc_theme_get_archives_link');

Monday, September 16, 2013

jQuery scrolling dynamic content Box


jQuery(document).ready(function($){
$(window).scroll(function() {
var windowHeight = $(window).height();
var documentHeight = $(document).height();
var footerHeight = $(".footer-container").height();
if($(window).scrollTop() >= ($(document).height() - $(window).height() - footerHeight)) {
if($(".news_listing .news_showmore").length == 1){
if($(".news_listing .news_showmore").hasClass("hasloader") == false){
$(".news_listing .news_showmore").addClass("hasloader");
$(".loadmoreimg").show();
/* Write your ajax code here*/
}
}
}
});
});

Wednesday, September 11, 2013

Recent posts widget, with limited text and 'read more' link - wordpress - [resolved]

Please write below code in functions.php


add_action( 'widgets_init', 'switch_recent_posts_widget' );

function switch_recent_posts_widget() {

    unregister_widget( 'WP_Widget_Recent_Posts' );
    register_widget( 'WP_Widget_Recent_Posts_Truncated' );

}

class WP_Widget_Recent_Posts_Truncated extends WP_Widget {

    function __construct() {
        $widget_ops = array('classname' => 'widget_recent_entries', 'description' => __( "The most recent posts on your site") );
        parent::__construct('recent-posts', __('Recent Posts'), $widget_ops);
        $this->alt_option_name = 'widget_recent_entries';

        add_action( 'save_post', array(&$this, 'flush_widget_cache') );
        add_action( 'deleted_post', array(&$this, 'flush_widget_cache') );
        add_action( 'switch_theme', array(&$this, 'flush_widget_cache') );
    }

    function widget($args, $instance) {
        $cache = wp_cache_get('widget_recent_posts', 'widget');

        if ( !is_array($cache) )
            $cache = array();

        if ( isset($cache[$args['widget_id']]) ) {
            echo $cache[$args['widget_id']];
            return;
        }

        ob_start();
        extract($args);

        $title = apply_filters('widget_title', empty($instance['title']) ? __('Recent Posts') : $instance['title'], $instance, $this->id_base);
        if ( ! $number = absint( $instance['number'] ) )
            $number = 10;

        $r = new WP_Query(array('posts_per_page' => $number, 'no_found_rows' => true, 'post_status' => 'publish', 'ignore_sticky_posts' => true));
        if ($r->have_posts()) :
?>
        <?php echo $before_widget; global $post ?>
        <?php if ( $title ) echo $before_title . $title . $after_title; ?>
        <ul>
        <?php  while ($r->have_posts()) : $r->the_post(); ?>
        <li><a href="<?php the_permalink() ?>" title="<?php echo esc_attr(get_the_title() ? get_the_title() : get_the_ID()); ?>">
            <?php
echo (strlen(get_the_title()) > 25)?substr(get_the_title(),0,25).'...':get_the_title();
            ?>
        </a></li>
        <?php endwhile; ?>
        </ul>
        <?php echo $after_widget; ?>
<?php
        // Reset the global $the_post as this query will have stomped on it
        wp_reset_postdata();

        endif;

        $cache[$args['widget_id']] = ob_get_flush();
        wp_cache_set('widget_recent_posts', $cache, 'widget');
    }

    function update( $new_instance, $old_instance ) {
        $instance = $old_instance;
        $instance['title'] = strip_tags($new_instance['title']);
        $instance['number'] = (int) $new_instance['number'];
        $this->flush_widget_cache();

        $alloptions = wp_cache_get( 'alloptions', 'options' );
        if ( isset($alloptions['widget_recent_entries']) )
            delete_option('widget_recent_entries');

        return $instance;
    }

    function flush_widget_cache() {
        wp_cache_delete('widget_recent_posts', 'widget');
    }

    function form( $instance ) {
        $title = isset($instance['title']) ? esc_attr($instance['title']) : '';
        $number = isset($instance['number']) ? absint($instance['number']) : 5;
?>
        <p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
        <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></p>

        <p><label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('Number of posts to show:'); ?></label>
        <input id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php echo $number; ?>" size="3" /></p>
<?php
    }
}

Saturday, September 7, 2013

Woocommerce Products show on homepage with pagination

Please first install "WP-Pagenavi" plugin to your store.
and then write below code to your home page template.

<?php
                // Setup your custom query
                global $paged;
                if( get_query_var( 'paged' ) )
                $my_page = get_query_var( 'paged' );
                else {
                if( get_query_var( 'page' ) )
                $my_page = get_query_var( 'page' );
                else
                $my_page = 1;
                set_query_var( 'paged', $my_page );
                $paged = $my_page;
                }
                $args = array( 'post_type' => 'product', 'paged' => $my_page, 'posts_per_page' => 8 );
                $loop = new WP_Query( $args );
                //print_r($loop);
                echo '<ul>';
                while ( $loop->have_posts() ) : $loop->the_post();
                   
                    echo '<li class="product">';
                            echo '<a class="prod_image" href="'.esc_url( get_permalink( $post->ID ) ).'" title="'.esc_attr($post->post_title ? $post->post_title : $post->ID).'">';
                            if ( has_post_thumbnail($post->ID) ) {
                                echo get_the_post_thumbnail( $post->ID, apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ) );
                            } else {
                                echo apply_filters( 'woocommerce_single_product_image_html', sprintf( '<img src="%s" alt="Placeholder" />', woocommerce_placeholder_img_src() ), $post->ID );
                            }
                            echo '</a>';                               
                            if(get_post_meta( $post->ID, '_regular_price', true) != ''){
                                echo '<span class="price"><span class="amount">$'.number_format(get_post_meta( $post->ID, '_regular_price', true), 2, '.', '').'</span></span>';
                            } else {
                                echo '<span class="price"><span class="amount">&nbsp;</span></span>';
                            }
                            echo '<p>'.substr(strip_tags($post->post_content),0,25).'...</p>';
                            echo '<div class="info"><a href="'.get_permalink().'">INFO</a></div>';
                       
                    echo '</li>';
                endwhile;
                wp_pagenavi(array( 'query' => $loop ));
                wp_reset_query();
                ?>

Friday, September 6, 2013

[resolved] WP-PageNavi with custom query and $paged variable


<?php

global $paged;
if( get_query_var( 'paged' ) )
$my_page = get_query_var( 'paged' );
else {
if( get_query_var( 'page' ) )
$my_page = get_query_var( 'page' );
else
$my_page = 1;
set_query_var( 'paged', $my_page );
$paged = $my_page;
}

$jobquery = new WP_Query( array( 'post_status' => 'publish', 'post_type' => 'job', 'paged' => $my_page )  );
if(count($jobquery->posts) > 0){
foreach($jobquery->posts as $jpost) {

?> <header class="entry-header">
<h1 class="entry-title"><?php echo $jpost->post_title; ?></h1>
</header><!-- .entry-header -->

<div class="entry-content">
<?php echo $jpost->post_content; ?>
</div><!-- .entry-content -->

<?php } wp_pagenavi( array( 'query' => $jobquery ) ); ?>
<?php }  wp_reset_query(); ?>

Thursday, September 5, 2013

How to Add Placeholder Text in Gravity Forms


To do that, you need to open your theme’s functions.php file and paste the following code:

/* Add a custom field to the field editor (See editor screenshot) */
add_action("gform_field_standard_settings", "my_standard_settings", 10, 2);

function my_standard_settings($position, $form_id){
// Create settings on position 25 (right after Field Label)
if($position == 25){
?>
<li class="admin_label_setting field_setting" style="display: list-item; ">
<label for="field_placeholder">Placeholder Text<!-- Tooltip to help users understand what this field does -->
<a href="javascript:void(0);" class="tooltip tooltip_form_field_placeholder" tooltip="&lt;h6&gt;Placeholder&lt;/h6&gt;Enter the placeholder/default text for this field.">(?)</a>
</label>
<input type="text" id="field_placeholder" class="fieldwidth-3" size="35" onkeyup="SetFieldProperty('placeholder', this.value);">
</li>
<?php
}
}

/* Now we execute some javascript technicalitites for the field to load correctly */
add_action("gform_editor_js", "my_gform_editor_js");

function my_gform_editor_js(){
?>
<script>
jQuery(document).bind("gform_load_field_settings", function(event, field, form){
jQuery("#field_placeholder").val(field["placeholder"]);
});
</script>
<?php
}

/* We use jQuery to read the placeholder value and inject it to its field */
add_action('gform_enqueue_scripts',"my_gform_enqueue_scripts", 10, 2);
function my_gform_enqueue_scripts($form, $is_ajax=false){
?>
<script>
jQuery(function(){
<?php
/* Go through each one of the form fields */
foreach($form['fields'] as $i=>$field){
/* Check if the field has an assigned placeholder */
if(isset($field['placeholder']) && !empty($field['placeholder'])){
/* If a placeholder text exists, inject it as a new property to the field using jQuery */
?>
jQuery('#input_<?php echo $form['id']?>_<?php echo $field['id']?>').attr('placeholder','<?php echo $field['placeholder']?>');
<?php
}
}
?>
});
</script>
<?php
}

Reference URL: http://www.wpbeginner.com/wp-tutorials/how-to-add-placeholder-text-in-gravity-forms/

Wednesday, September 4, 2013

Wordpress get menu list


$menu_name = 'primary';

    if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );

$menu_items = wp_get_nav_menu_items($menu->term_id);

$menu_list = '<ul id="menu-' . $menu_name . '">';

foreach ( (array) $menu_items as $key => $menu_item ) {
$title = $menu_item->title;
$url = $menu_item->url;
$menu_list .= '<li><a href="' . $url . '">' . $title . '</a></li>';
}
$menu_list .= '</ul>';
    } else {
$menu_list = '<ul><li>Menu "' . $menu_name . '" not defined.</li></ul>';
    }
echo $menu_list;

Tuesday, September 3, 2013

How To: Enable the Use of Sessions On Your WordPress - [Resolved]


If you want to activate session variables within your WordPress installation the only thing you have to do is call session_start(); before any output is send to the client. Normally upgrading your WordPress installation will replace all files, so we will want to install the code within our site theme to avoid the changes from being lost.

We will add the next lines of code to our functions.php file within our theme:

if ( !session_id() )
add_action( 'init', 'session_start' );



It is best place to add these lines is at the top of functions.php, immediately after the php start tag (<?php).

Tuesday, August 27, 2013

wordpress get attachment id by url


function wp_get_attachment_id_from_url( $attachment_url = '' ) {

global $wpdb;
$attachment_id = false;

// If there is no url, return.
if ( '' == $attachment_url )
return;

// Get the upload directory paths
$upload_dir_paths = wp_upload_dir();

// Make sure the upload path base directory exists in the attachment URL, to verify that we're working with a media library image
if ( false !== strpos( $attachment_url, $upload_dir_paths['baseurl'] ) ) {

// If this is the URL of an auto-generated thumbnail, get the URL of the original image
$attachment_url = preg_replace( '/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $attachment_url );

// Remove the upload path base directory from the attachment URL
$attachment_url = str_replace( $upload_dir_paths['baseurl'] . '/', '', $attachment_url );

// Finally, run a custom database query to get the attachment ID from the modified attachment URL
$attachment_id = $wpdb->get_var( $wpdb->prepare( "SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = '_wp_attached_file' AND wpostmeta.meta_value = '%s' AND wposts.post_type = 'attachment'", $attachment_url ) );

}

return $attachment_id;
}

Wordpress insert new post status

Please write below code in your functions.php


function deactive_post_status_removed(){
register_post_status( 'removed', array(
'label'                     => _x( 'Removed', 'post' ),
'public'                    => false,
'exclude_from_search'       => true,
'show_in_admin_all_list'    => true,
'show_in_admin_status_list' => true,
'label_count'               => _n_noop( 'Removed <span class="count">(%s)</span>', 'Removed <span class="count">(%s)</span>' ),
) );
}
add_action( 'init', 'deactive_post_status_removed' );

I have use this code for deactivate post status

Jquery input label toggle effect


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
(function($){$.fn.overlabel=function(options){var opts=$.extend({},$.fn.overlabel.defaults,options);var selection=this.filter('label[for]').map(function(){var label=$(this);var id=label.attr('for');var field=document.getElementById(id);if(!field)return;if(label.hasClass('cms-overlabel-active')==false){var o=$.meta?$.extend({},opts,label.data()):opts;label.addClass(o.label_class).addClass('cms-overlabel-active');var hide_label=function(){label.hide();label.data('shown',0);};var show_label=function(){if(!this.value&&label.data('shown')!=1){label.fadeIn('fast');label.data('shown',1);}else if(this.value&&label.data('shown')==1){label.hide();label.data('shown',0);}};var p=$(field).position();var h=parseInt($(field).height().toString().replace('px',''),10);var fsRaw=$(field).css('font-size');var fs=parseInt(fsRaw.replace('px',''),10);if(fs>h){fsRaw=$(field).parent().css('font-size');}
label.css({'top':p.top+'px','left':p.left+'px','padding-top':parseInt($(field).css("padding-top"))+'px','padding-left':(parseInt($(field).css("padding-left"))+2)+'px','font-family':$(field).css("font-family"),'font-size':fsRaw});$(field).focus(hide_label).blur(show_label).change(show_label).each(hide_label).each(show_label);}
return this;});return opts.filter?selection:selection.end();};$.fn.overlabel.defaults={label_class:'cms-label-dynamic',hide_css:{'text-indent':'-10000px'},show_css:{'text-indent':'0px','cursor':'text'},filter:false};})(jQuery);
</script>
</head>
<body>
<div class="cms-label-watermark-wrap">
<label for="first_name" class="cms-label-watermark">First Name</label>
<input class="" type="text" size="30" name="first_name" id="first_name" value="" />
</div>


<script type="text/javascript">
$(document).ready(function(){
$('label.cms-label-watermark').overlabel();
});
</script>

</body>
</html>

Thursday, August 22, 2013

Restrict admin panel from front user in wordpress


add_action( 'init', 'blockusers_init' );
function blockusers_init() {
    if ( is_admin() && ! current_user_can( 'administrator' ) && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
        wp_redirect( home_url() );
        exit;
    }
}

Sunday, August 18, 2013

WooCommerce - Show number of items in cart and total

<?php global $woocommerce; ?>

<a class="cart-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> - <?php echo $woocommerce->cart->get_cart_total(); ?></a>

Woocommerce - disable/removing products descriptions tabs

Please write below code in functions.php

add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 );
function woo_remove_product_tabs( $tabs ) {   
    unset( $tabs['description'] ); // Remove the description tab
    //unset( $tabs['reviews'] ); // Remove the reviews tab
    //unset( $tabs['additional_information'] ); // Remove the additional information tab
   
    return $tabs;
}

Tuesday, August 13, 2013

PHP get week number from date



function get_week_number_by_date($date) {

$today = $date;
$currentDay = date("w", strtotime($date));
$todate = date('Y-m-d', strtotime($date));
$myTime = $todate." 18:00:00";

$weekNumber = date("W", strtotime("0 day", strtotime($date)));

if($currentDay == 0){
if(strtotime($today) > strtotime($myTime)){
$weekNumber = date("W", strtotime("1 day", strtotime($date)));
}
}
return $weekNumber;
}

In this example I have setup "sunday 6:00 PM" as a week start day.

Tuesday, July 30, 2013

Wordpress image upload using url or from external site



     
      $filepath = dirname(__FILE__) . '/' . $filename;

$wp_filetype = wp_check_filetype($filepath, null );
$uploads = wp_upload_dir();

$fullpathfilename = $uploads['path'] . "/" . $filename;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, get_template_directory_uri().'/youtubeupload/'.$filename);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$image_string = curl_exec($ch);
curl_close($ch);

$fileSaved = file_put_contents($uploads['path'] . "/" . $filename, $image_string);
if ( !$fileSaved ) {
echo "The file cannot be saved.";
}

$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $uploads['url'] . "/" . $filename
);
$attach_id = wp_insert_attachment( $attachment, $fullpathfilename );
if ( !$attach_id ) {
echo "Failed to save record into database.";
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullpathfilename );
wp_update_attachment_metadata( $attach_id,  $attach_data );

set_post_thumbnail( $post_id, $attach_id );

Tuesday, July 16, 2013

jQuery Countdown time - show timer with two digits

If you are using countdown jquery from "http://keith-wood.name/countdown.html" then please open "jquery.countdown.js" and replace below code:

line no: 520 - 528

Original Code

var showFull = function(period) {
var labelsNum = inst.options['labels' + whichLabels(inst._periods[period])];
return ((!inst.options.significant && show[period]) ||
(inst.options.significant && showSignificant[period]) ?
'<span class="' + plugin._sectionClass + '">' +
'<span class="' + plugin._amountClass + '">' +
self._translateDigits(inst, inst._periods[period]) + '</span><br/>' +
(labelsNum ? labelsNum[period] : labels[period]) + '</span>' : '');
};



New Code

var showFull = function(period) {
var labelsNum = inst.options['labels' + whichLabels(inst._periods[period])];

return ((!inst.options.significant && show[period]) ||
(inst.options.significant && showSignificant[period]) ?
'<span class="' + plugin._sectionClass + '">' +
'<span class="' + plugin._amountClass + '">' + ((self._translateDigits(inst, inst._periods[period]) <= 9 )?'0'+self._translateDigits(inst, inst._periods[period]):self._translateDigits(inst, inst._periods[period])) + '</span><br/>' +
(labelsNum ? labelsNum[period] : labels[period]) + '</span>' : '');
};



Monday, July 15, 2013

PHP code to add st, nd, rd or th to a number



function wp_get_ordinal($input_number)
{
  $number            = (string) $input_number;
  $last_digit        = substr($number, -1);
  $second_last_digit = substr($number, -2, 1);
  $suffix            = 'th';
  if ($second_last_digit != '1')
  {
    switch ($last_digit)
    {
      case '1':
        $suffix = 'st';
        break;
      case '2':
        $suffix = 'nd';
        break;
      case '3':
        $suffix = 'rd';
        break;
      default:
        break;
    }
  }
  if ((string) $number === '1') $suffix = 'st';
  return $number.$suffix;
}

Friday, July 12, 2013

mysql count like and dislike average from one column


likes_id video_id Descending user_id like_status like_ip datetime
13 290 2 y 2013-07-01 17:15:29
25 290 3 y 2013-07-01 17:26:12
42 290 9 y 2013-07-01 17:30:35
58 290 10 n 183.182.91.153 2013-07-12 04:52:44

SELECT `like_status` , count( * ) FROM video_likes WHERE video_id = 290 GROUP BY `like_status`



like_status count( * )
y 3
n 1

SELECT SUM( CASE WHEN like_status = 'y' THEN 1 ELSE -1 END) as `counts` FROM `wp_video_likes`  WHERE video_id = 290;

PHP Cron setup




/usr/local/bin/php /home/ABC/public_html/plonk/cron.php>/home/ABC/public_html/cron/cronlog_`date "+\%Y-\%m-\%d_\%H-\%M"`.txt

Thursday, July 11, 2013

How to get youtube video duration from id - PHP



function parseVideoEntry($video_id) {    
    $obj= new stdClass;

$url = 'http://gdata.youtube.com/feeds/api/videos/'.$video_id;
$categoriesArray = array();
$xml = simplexml_load_file($url);


    $media = $xml->children('http://search.yahoo.com/mrss/');
    $obj->title = $media->group->title;
    $obj->description = $media->group->description;
     
    $yt = $media->children('http://gdata.youtube.com/schemas/2007');
    $attrs = $yt->duration->attributes();

    $obj->length = $attrs['seconds'];
    $VideoSeconds = $obj->length;
    return $VideoSeconds;    
}

echo $video = parseVideoEntry("nVhM3IYMF8o");

Convert seconds to hours, minutes and seconds - PHP


function secondsToWords($seconds)
{
    /*** return value ***/
    $ret = "";

    /*** get the hours ***/
    $hours = intval(intval($seconds) / 3600);
    if($hours > 0)   {
        if($hours <= 9) { $ret .= "0".$hours.":";}
else {       $ret .= $hours.":";}
    }
    /*** get the minutes ***/
    $minutes = bcmod((intval($seconds) / 60),60);
    if($hours > 0 || $minutes > 0)
    {
if($minutes <= 9) { $ret .= "0".$minutes.":";}
else {       $ret .= $minutes.":";}
    }
 
    /*** get the seconds ***/
    $seconds = bcmod(intval($seconds),60);
if($seconds <= 9) { $ret .= "0".$seconds;}
else {       $ret .= $seconds;}

    return $ret;
}

echo secondsToWords(3725);

How to detect video file duration in minutes with PHP?



ob_start();
 passthru("D:/wamp/www/ffmpeg/ffmpeg.exe -i D:/wamp/www/video5.mp4  2>&1");
 $duration = ob_get_contents();
 $full = ob_get_contents();
 ob_end_clean();
 $search = "/Duration.*?([0-9]{1,}):([0-9]{1,}):([0-9]{1,})/";
 print_r($duration);
 $duration = preg_match($search, $duration, $matches, PREG_OFFSET_CAPTURE, 3);

 print_r($matches);
 print_r($matches[1][0]);

Monday, July 8, 2013

Get Youtube video id from embaded code - PHP

function parse_youtube($link){

    $regexstr = '~
        # Match Youtube link and embed code
        (?:                             # Group to match embed codes
            (?:<iframe [^>]*src=")?       # If iframe match up to first quote of src
            |(?:                        # Group to match if older embed
                (?:<object .*>)?      # Match opening Object tag
                (?:<param .*</param>)*  # Match all param tags
                (?:<embed [^>]*src=")?  # Match embed tag to the first quote of src
            )?                          # End older embed code group
        )?                              # End embed code groups
        (?:                             # Group youtube url
            https?:\/\/                 # Either http or https
            (?:[\w]+\.)*                # Optional subdomains
            (?:                         # Group host alternatives.
            youtu\.be/                  # Either youtu.be,
            | youtube\.com              # or youtube.com
            | youtube-nocookie\.com     # or youtube-nocookie.com
            )                           # End Host Group
            (?:\S*[^\w\-\s])?           # Extra stuff up to VIDEO_ID
            ([\w\-]{11})                # $1: VIDEO_ID is numeric
            [^\s]*                      # Not a space
        )                               # End group
        "?                              # Match end quote if part of src
        (?:[^>]*>)?                       # Match any extra stuff up to close brace
        (?:                             # Group to match last embed code
            </iframe>                 # Match the end of the iframe
            |</embed></object>          # or Match the end of the older embed
        )?                              # End Group of last bit of embed code
        ~ix';

    preg_match($regexstr, $link, $matches);
    return $matches[1];
}

function get_youtube_id($embadedcode){
 if(strpos($embadedcode,'iframe') !== false){
  return parse_youtube($embadedcode);
 } else if(strpos($embadedcode,'object') !== false){
  preg_match('#(?<=youtube\.com/v/)\w+#', $embadedcode, $matches);
  return $matches[0];
 }
}

Wordpress Upload media file from front-end


$filename = rand(1000, 10000) . str_replace(" ","-",$_FILES["video_thumbnail"]["name"]);


require_once(ABSPATH . '/wp-load.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/image.php');

$upload_overrides = array( 'test_form' => FALSE );
$uploads = wp_upload_dir();

$file_array = array(
'name' => $filename,
'type' => $_FILES['video_thumbnail']['type'],
'tmp_name' => $_FILES['video_thumbnail']['tmp_name'],
'error' => $_FILES['video_thumbnail']['error'],
'size' => $_FILES['video_thumbnail']['size'],
);

$uploaded_file = wp_handle_upload( $file_array, $upload_overrides );

$wp_filetype = wp_check_filetype( basename( $uploaded_file['file'] ), null );

$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit'
);
$uploadfile = $uploads['path'].'/' . basename( $filename );

$attachment_id = wp_insert_attachment( $attachment, $uploadfile );

$attach_data = wp_generate_attachment_metadata( $attachment_id, $uploadfile );

$attachimage_url = $uploads['url'].'/'.basename( $filename ) ;
wp_update_attachment_metadata( $attachment_id, $attach_data );

echo json_encode(array($attachment_id, $attachimage_url));

Monday, June 24, 2013

Redirect to home page if query string not match to value - wordpress


Please add below code to "functions.php" for generating the query string:

function add_query_vars($aVars) {
    $aVars[] = "mode";
    return $aVars;
}

add_filter('query_vars', 'add_query_vars');

function add_rewrite_rules($aRules) {
    $aNewRules = array('news/([^/]+)/?$' => 'index.php?pagename=news&mode=$matches[1]');
    $aRules = $aNewRules + $aRules;
    return $aRules;
}

add_filter('rewrite_rules_array', 'add_rewrite_rules');

function wp_redirect_to_homepage( $query ) {    
 if ( $query->is_main_query() && ( $query->query_vars['pagename'] == 'news') ){         
        if( ( array_key_exists( 'mode', $query->query_vars ) && (trim($query->query_vars['mode']) != 'follow' && trim($query->query_vars['mode']) != 'like'))) {
            wp_redirect( get_permalink($query->queried_object_id) );
            exit;
        }   
    }
}
add_action( 'parse_query', 'wp_redirect_to_homepage' );


Also you can see below URL:
http://stackoverflow.com/questions/14669336/redirect-if-wordpress-query-string-is-empty 
Its very good example for rewrite query string.

Wednesday, June 12, 2013

How to redirect non-admin users to home page (wordpress)? [resolved]


Please write below code in functions.php

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

Wordpress disable admin panel for all user [resolved]


Please write below code into functions.php

function drop_hide_admin_bar_settings() {
?>
<style type="text/css">
.show-admin-bar {
display: none;
}
</style>
<?php
}

function drop_disable_admin_bar() {
   if (!current_user_can('administrator')) {
add_filter( 'show_admin_bar', '__return_false' );
add_action( 'admin_print_scripts-profile.php', 'drop_hide_admin_bar_settings' );
   }
}

add_action( 'init', 'drop_disable_admin_bar' , 9 );

Tuesday, June 11, 2013

Allow WordPress login using Email Address


Please add below code to admin panel

function login_with_email_address($username) {
$user = get_user_by_email($username);
if(!empty($user->user_login))
$username = $user->user_login;
return $username;
}
add_action('wp_authenticate','login_with_email_address');

Create options pages in wordpress admin panel


Please write below code in functions.php


<?php
add_action('admin_menu', 'yt_menu');
function yt_menu() {
  add_menu_page('YT Options', 'yt Uploader', 'manage_options', 'yt-identifier', 'yt_options_page', '', 30);
}

function yt_register_settings() {
register_setting( 'yt_theme_options', 'yt_options');
}
add_action( 'admin_init', 'yt_register_settings' );

/*
Above, we have simply created a new function for registering the new option (YT Options) using the register setting wordpress function. The most important part of the above code is the “add_menu_page” bit, which is the code that actually adds a new menu item to the admin panel named “YT Options”.

We have successfully created a new menu item, specifically for changing the text on YT Options.  Now we need to create some content for this new page. Add the following code directly below what code you have already added:
*/

function yt_options_page() {
global $yt_options, $yt_categories, $yt_layouts;

if (!current_user_can('manage_options'))  {
wp_die( __('You do not have sufficient permissions to access this page.') );
}

echo '<div class="wrap"><h2>Change your yt uploader settings</h2></div>';
?>

<form id="yt_auth_options" method="post" action="options.php">
<?php $settings = get_option( 'yt_options', $yt_options ); ?>
<?php settings_fields( 'yt_theme_options' ); ?>
<table class="form-table">
<tbody
<tr valign="top">
<td colspan="2">
<div id="auth_options">
<div>
Username : <label title="username"><input type="text" name="yt_options[username]" value="<?php echo stripslashes($settings['username']); ?>"></label>
<br>Password : <label title="password"><input type="password" name="yt_options[password]" value="<?php echo stripslashes($settings['password']); ?>"></label>
</div>
</div><br>
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Save settings" class="button-primary"> <input type="hidden" value="1" name="yt_uploader_settings"></form>

<?php
}
?>

The code above first of all gives our new page a title that is in-keeping with the style of our admin area. Next up, we define what message to display when our text has been updated. We then create our form for actually entering and editing the options. We then validate the value of this text and return it to be stored, using options.php.

Wordpress login/registration using ajax - [resolved]


Please write below code in functions.php
-----------------------------------------------------------------------------------------------------------

<?php
function ajax_login_init(){

    wp_register_script('ajax-login-script', get_template_directory_uri() . '/js/ajax-login-script.js', array('jquery') );
    wp_enqueue_script('ajax-login-script');

    wp_localize_script( 'ajax-login-script', 'ajax_login_object', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'redirecturl' => home_url(),
        'loadingmessage' => __('Sending user info, please wait...')
    ));

    // Enable the user with no privileges to run ajax_login() in AJAX
    add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
}

// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
    add_action('init', 'ajax_login_init');
}

function ajax_login(){

    // First check the nonce, if it fails the function will break
    check_ajax_referer( 'ajax-login-nonce', 'security' );

    // Nonce is checked, get the POST data and sign user on
    $info = array();
    $info['user_login'] = $_POST['username'];
    $info['user_password'] = $_POST['password'];
    $info['remember'] = true;

    $user_signon = wp_signon( $info, false );
    if ( is_wp_error($user_signon) ){
        echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
    } else {
        echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
    }

    die();
}

function ajax_registration_init(){

    wp_localize_script( 'ajax-login-script', 'ajax_registration_object', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'redirecturl' => home_url(),
        'loadingmessage' => __('Sending user info, please wait...')
    ));

    // Enable the user with no privileges to run ajax_login() in AJAX
    add_action( 'wp_ajax_nopriv_ajaxregistration', 'ajax_registration' );
}

// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
    add_action('init', 'ajax_registration_init');
}

function ajax_registration(){

    // First check the nonce, if it fails the function will break
    check_ajax_referer( 'ajax-registration-nonce', 'regsecurity' );

    // Nonce is checked, get the POST data and sign user on
    $info = array();
   
    $regname = $_POST['regname'];
    $regemail = $_POST['regemail'];
$regusername = explode("@",$regemail);
$regusername = $regusername[0];
$regpassword = $_POST['regpassword'];

$myerror = '';

if($regemail == ''){
$myerror .= 'Please enter email address';
}
else if($regpassword == ''){
$myerror .= ($myerror != '')?'<br>':'';
$myerror .= 'Please enter password';
}
if($myerror != ''){
echo json_encode(array('signupresponse'=>false, 'message'=>__("$myerror")));
}
else {
if ( email_exists($regemail) == false ) {
$user_id = wp_create_user( $regusername, $regpassword, $regemail );
update_user_option( $user_id, 'firstname', $regname);
echo json_encode(array('signupresponse'=>true, 'message'=>__('Register successful!\n You can login now')));
} else {
echo json_encode(array('signupresponse'=>false, 'message'=>__('Email already exists.')));
}
}

    die();
}
?>
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
Now create "ajax-login-script.js" file 
-----------------------------------------------------------------------------------------------------------
jQuery(document).ready(function($) {

    // Show the login dialog box on click
    $('a#show_login').on('click', function(e){
        $('body').prepend('<div class="login_overlay"></div>');
        $('form#login').fadeIn(500);
        $('div.login_overlay, form#login a.close').on('click', function(){
            $('div.login_overlay').remove();
            $('form#login').hide();
        });
        e.preventDefault();
    });

    // Perform AJAX login on form submit
    $('form#login').on('submit', function(e){
        $('form#login p.status').show().text(ajax_login_object.loadingmessage);
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_login_object.ajaxurl,
            data: { 
                'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin
                'username': $('form#login #username').val(), 
                'password': $('form#login #password').val(), 
                'security': $('form#login #security').val() },
            success: function(data){
                $('form#login p.status').text(data.message);
                if (data.loggedin == true){
                    document.location.href = ajax_login_object.redirecturl;
                }
            }
        });
        e.preventDefault();
    });

// Show the login dialog box on click
    $('a#show_registration').on('click', function(e){
        $('body').prepend('<div class="login_overlay"></div>');
        $('form#registration').fadeIn(500);
        $('div.login_overlay, form#registration a.close').on('click', function(){
            $('div.login_overlay').remove();
            $('form#registration').hide();
        });
        e.preventDefault();
    });

    // Perform AJAX registration on form submit
    $('form#registration').on('submit', function(e){
        $('form#registration p.status').show().text(ajax_registration_object.loadingmessage);
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_registration_object.ajaxurl,
            data: { 
                'action': 'ajaxregistration', //calls wp_ajax_nopriv_ajaxregistration
                'regname': $('form#registration #regname').val(), 
                'regemail': $('form#registration #regemail').val(), 
                'regpassword': $('form#registration #regpassword').val(), 
                'regsecurity': $('form#registration #regsecurity').val() },
            success: function(data){
                $('form#registration p.status').text(data.message);
                if (data.signupresponse == true){
                    document.location.href = ajax_registration_object.redirecturl;
                }
            }
        });
        e.preventDefault();
    });
});
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
Please add below code after body tag in header.php
-----------------------------------------------------------------------------------------------------------
<form id="login" action="login" method="post">
        <h1>Site Login</h1>
        <p class="status"></p>
        <label for="username">Username</label>
        <input id="username" type="text" name="username">
        <label for="password">Password</label>
        <input id="password" type="password" name="password">
        <a class="lost" href="<?php echo wp_lostpassword_url(); ?>">Lost your password?</a>
        <input class="submit_button" type="submit" value="Login" name="submit">
        <a class="close" href="">(close)</a>
        <?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>
<?php do_action( 'wordpress_social_login' ); ?>
    </form>

<form id="registration" action="registration" method="post">
        <h1>Site Registration</h1>
        <p class="status"></p>
        <label for="regname">Name</label>
        <input id="regname" type="text" name="regname">
        <label for="regemail">Email</label>
        <input id="regemail" type="text" name="regemail">
        <label for="regpassword">Password</label>
        <input id="regpassword" type="password" name="regpassword">
        <input class="submit_button" type="submit" value="Registration" name="submit">
        <a class="close" href="">(close)</a>
        <?php wp_nonce_field( 'ajax-registration-nonce', 'regsecurity' ); ?>
    </form>

after this add below code for "login/logout" link
<?php if (is_user_logged_in()) { ?>
<a class="login_button" href="<?php echo wp_logout_url( home_url() ); ?>">Logout</a>
<?php } else { ?>
<a class="login_button" id="show_login" href="">Login</a> &nbsp;&nbsp;<a class="registration_button" id="show_registration" href="">SignUp</a>
<?php } ?>
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
Please add below CSS code into your style.css 
-----------------------------------------------------------------------------------------------------------
form#login, form#registration{
    display: none;
    background-color: #FFFFFF;
    border-radius: 8px;
    font-family: Arial, Helvetica, sans-serif;
    box-shadow: 0 0 6px rgba(0, 0, 0, 0.2);
    position: fixed;
    top: 200px;
    padding: 40px 25px 25px 25px;
    width: 350px;
    z-index: 999;
    left: 50%;
    margin-left: -200px;
    color: #878787;
    font-size: 11px;
}

form#login h1, form#registration h1{
    color: #333333;
    font-family: 'Georgia', 'Times New Roman', Times, serif;
    font-size: 27px;
    font-weight: 100;
    text-align: center;
    line-height: 1;
    margin: 0 0 30px 0;
}

form#login input#username,
form#login input#password,
form#registration input#regname,
form#registration input#regemail,
form#registration input#regpassword{
    border: 1px solid #EDEDED;
    border-radius: 3px 3px 3px 3px;
    box-shadow: 0 0 3px rgba(0, 0, 0, 0.1) inset;
    color: #333333;
    font-size: 15px;
    padding: 10px 10px 10px 13px;
    width: 325px;
    margin: 7px 0 30px 0;
    background-color: #F9F9F9;
    font-family: 'Georgia', 'Times New Roman', Times, serif;
}

form#login input#username:focus,
form#login input#username:focus,
form#registration input#regname:focus,
form#registration input#regemail:focus,
form#registration input#regpassword:focus{
    background-color: #FFF;
}


form#login input.submit_button, form#registration input.submit_button{
    font-size: 13px;
    color: #FFF;
    border: 1px solid #b34336;
    background-color: #e25c4c;
    border-radius: 3px;
    text-shadow: 0 1px 0 #ba3f31;
    padding: 9px 31px 9px 31px;
    background: -moz-linear-gradient(top, #ea6656, #df5949);
    border-top: 1px solid #bb483a;
    border-bottom: 1px solid #a63b2e;
    float: right;
    box-shadow: 0 1px 0 #E87A6E inset;
}

form#login a, form#registration a{
    text-decoration: none;
}

form#login a.close, form#registration a.close{
    color: #DCDCDC;
    position: absolute;
    right: 15px;
    top: 15px;
}

form#login a.lost, form#registration a.lost{
    color: #B4B2B2;
    float: left;
    margin: 10px 0 0 0;
}

form#login p.status, form#registration p.status{
    text-align: center;
    margin: -25px 0 20px 0;
    display: none;
}

a.login_button, a.registration_button{
    font-family: Arial, Helvetica, sans-serif;
    padding: 5px 7px 5px 7px;
    background-color: #FFF;
    border-radius: 3px;
    border: 1px solid #DCDCDC;
    color: #333;
    text-decoration: none;
    font-size: 11px;
}

.login_overlay{
    height: 100%;
    width: 100%;
top: 0px;
    background-color: #F6F6F6;
    opacity: 0.9;
    position: fixed;
    z-index: 998;
}
-----------------------------------------------------------------------------------------------------------



Friday, April 19, 2013

Wordpress create new comment form



Please copy/paste below code in functions.php

function comment_form_new( $args = array(), $post_id = null ) {
global $user_identity, $id;

if ( null === $post_id )
$post_id = $id;
else
$id = $post_id;

$commenter = wp_get_current_commenter();

$req = get_option( 'require_name_email' );
$aria_req = ( $req ? " aria-required='true'" : '' );
$fields =  array(
'author' => '<p class="comment-form-author">' . '<label for="author">' . __( 'Name' ) . '</label> ' . ( $req ? '<span class="required">*</span>' : '' ) .
           '<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' /></p>',
'email'  => '<p class="comment-form-email"><label for="email">' . __( 'Email' ) . '</label> ' . ( $req ? '<span class="required">*</span>' : '' ) .
           '<input id="email" name="email" type="text" value="' . esc_attr(  $commenter['comment_author_email'] ) . '" size="30"' . $aria_req . ' /></p>',
'url'    => '<p class="comment-form-url"><label for="url">' . __( 'Website' ) . '</label>' .
           '<input id="url" name="url" type="text" value="' . esc_attr( $commenter['comment_author_url'] ) . '" size="30" /></p>',
);

$required_text = sprintf( ' ' . __('Required fields are marked %s'), '<span class="required"><a>*</a></span>' );
$defaults = array(
'fields'               => apply_filters( 'comment_form_default_fields', $fields ),
'comment_field'        => '<p class="comment-form-comment"><label for="comment">' . _x( 'Comment', 'noun' ) . '</label><textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea></p>',
'must_log_in'          => '<p class="must-log-in">' .  sprintf( __( 'You must be <a href="%s">logged in</a> to post a comment.' ), wp_login_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>',
'logged_in_as'         => '<p class="logged-in-as">' . sprintf( __( 'Logged in as <a href="%1$s">%2$s</a>. <a href="%3$s" title="Log out of this account">Log out?</a>' ), admin_url( 'profile.php' ), $user_identity, wp_logout_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>',
'comment_notes_before' => '<p class="comment-notes">' . __( 'Your email address will not be published.' ) . ( $req ? $required_text : '' ) . '</p>',

'id_form'              => 'commentform',
'id_submit'            => 'submit',
'title_reply'          => __( 'Leave <a>a Comment</a>' ),
'title_reply_to'       => __( 'Leave a Reply to %s' ),
'cancel_reply_link'    => __( 'Cancel reply' ),
'label_submit'         => __( 'Send Comment' ),
);

$args = wp_parse_args( $args, apply_filters( 'comment_form_defaults', $defaults ) );

?>
<?php if ( comments_open() ) : ?>
<?php do_action( 'comment_form_before' ); ?>
<div id="respond">
<h3 id="reply-title"><?php comment_form_title( $args['title_reply'], $args['title_reply_to'] ); ?> <small><?php cancel_comment_reply_link( $args['cancel_reply_link'] ); ?></small></h3>
<?php if ( get_option( 'comment_registration' ) && !is_user_logged_in() ) : ?>
<?php echo $args['must_log_in']; ?>
<?php do_action( 'comment_form_must_log_in_after' ); ?>
<?php else : ?>
<form action="<?php echo site_url( '/wp-comments-post.php' ); ?>" method="post" id="<?php echo esc_attr( $args['id_form'] ); ?>">
<?php do_action( 'comment_form_top' ); ?>
<?php if ( is_user_logged_in() ) : ?>
<?php echo apply_filters( 'comment_form_logged_in', $args['logged_in_as'], $commenter, $user_identity ); ?>
<?php do_action( 'comment_form_logged_in_after', $commenter, $user_identity ); ?>
<?php else : ?>
<?php echo $args['comment_notes_before']; ?>
<?php
do_action( 'comment_form_before_fields' );
foreach ( (array) $args['fields'] as $name => $field ) {
echo apply_filters( "comment_form_field_{$name}", $field ) . "\n";
}
do_action( 'comment_form_after_fields' );
?>
<?php endif; ?>
<?php echo apply_filters( 'comment_form_field_comment', $args['comment_field'] ); ?>
<?php echo $args['comment_notes_after']; ?>
<p class="form-submit">
<input name="submit" type="submit" id="<?php echo esc_attr( $args['id_submit'] ); ?>" value="<?php echo esc_attr( $args['label_submit'] ); ?>" />
<?php comment_id_fields(); ?>
</p>
<?php do_action( 'comment_form', $post_id ); ?>
</form>
<?php endif; ?>
</div><!-- #respond -->
<?php do_action( 'comment_form_after' ); ?>
<?php else : ?>
<?php do_action( 'comment_form_comments_closed' ); ?>
<?php endif; ?>
<?php
}

After this open "comments.php"

and replace "<?php comment_form(); ?>"

with "<?php comment_form_new(); ?>"