How to create widgets and call on front end in wordpress

widgets
Widgets is common things in wordpress but it is very use full to display short content and other information on content area or sidebar on front end area. If you create custom theme then you can create widgets with some code adding on themes functions.php file and call on frontend with one line code using name of widgets:

Just add this code on your functions.php file:


if (function_exists('register_sidebar')) {
register_sidebar(array(
'name'=> 'Home introduction',
'id' => 'top_tabs',
'before_widget' => '

  • ',
    'after_widget' => '

‘,
‘before_title’ => ‘

‘,
‘after_title’ => ‘

‘,
));
register_sidebar(array(
‘name’=> ‘Top Sidebar’,
‘id’ => ‘top_sidebar’,
‘before_widget’ => ‘

  • ‘,
    ‘after_widget’ => ‘

‘,
‘before_title’ => ‘

‘,
‘after_title’ => ‘

‘,
));
register_sidebar(array(
‘name’=> ‘Left Sidebar’,
‘id’ => ‘left_sidebar’,
‘before_widget’ => ‘

  • ‘,
    ‘after_widget’ => ‘

‘,
‘before_title’ => ‘

‘,
‘after_title’ => ‘

‘,
));
register_sidebar(array(
‘name’=> ‘Right Sidebar’,
‘id’ => ‘right_sidebar’,
‘before_widget’ => ‘

  • ‘,
    ‘after_widget’ => ‘

‘,
‘before_title’ => ‘

‘,
‘after_title’ => ‘

‘,
));
}

To call on front end where you want to display widgets using this code:


if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Home introduction') ) : endif;

Download code source file click on this link

Where ‘Home introduction’ is name of widgets which is used in functions.php.

Thanks, Cheers the code

Captcha using javascript

Basically we add captcha on form to stop spamming mail. I have used JavaScript captcha which I have mentioned below. May be it can help some one:

Add this code before submit button.

<form action=”thankyou.php” method=”post” name=”myform” onsubmit=”return checkForm();”>
<div class=”row”>
<div class=”col-md-6″>
<label>Please Enter Security Code*:</label><div id=”txtCaptcha”></div>
<input type=”text” name=”code” id=”txtInput” />
<span id=”ctcha” class=”commonerror”></span></div>
</div>
<input type=”submit” value=”Submit” />
</form>

 

//Created / Generates the captcha function
function DrawCaptcha()
{
var a = Math.ceil(Math.random() * 8)+ ”;
var b = Math.ceil(Math.random() * 8)+ ”;
var c = Math.ceil(Math.random() * 8)+ ”;
var d = Math.ceil(Math.random() * 8)+ ”;
var e = Math.ceil(Math.random() * 8)+ ”;

var code = a + b + c + d + e;
document.getElementById(“txtCaptcha”).innerHTML = code;
}
// Validate the Entered input aganist the generated security code function
// Remove the spaces from the entered and generated code
function removeSpaces(string)
{
return string.split(‘ ‘).join(”);
}

function checkForm()
{
var str1 = removeSpaces(document.getElementById(‘txtCaptcha’).innerHTML);
var str2 = removeSpaces(document.getElementById(‘txtInput’).value);
if (str1 == str2)
return true;
document.getElementById(“ctcha”).innerHTML=’Please enter correct code!’;
document.myform.txtInput.focus();
return false;

}
window.onload = DrawCaptcha();

 

Create template for products category in WP e-commerce

For this you need to follow the WordPress template hirerarchy for taxonomies. The taxonomy is wpsc_product_category.

Now use this way to create template:

Use : taxonomy-wpsc_product_category-[CATEGORY SLUG].php

So, if my category is Verragio, then WordPress will look for:

taxonomy-wpsc_product_category-verragio.php

Finally you need to upload the file then template page will work.

Lock certain post, category posts and pages with subscriber box in wordpress

I was working on a health project and client wants to lock some articles with subscribe box. When user subscribe the email id then he will get the confirmation mail, after confirmation mail the article or post become unlock. The subscriber mail id also store on admin.

subscriber-content-locker

I have searched after sometime I got subscriber content locker premium plugin but I got this free download after some search and thats not working properly then some working on plugin file and its working great.

adminscreenshot

if anybody need then you can download and use this:

Click for plugin download : Download Plugin

Note :This plugin work online not localhost.

Cheers! Enjoy the plugin and comment if you have any question.

Create custom post type in wordpress

As we know that many times we need to create seperate section for slider, testimonials etc. so that user can easily manage these things. For this we can create custom post type which is very easy to implement in wordpress.

Just follow the slider example:

For slider just copy this code in functions.php of your theme file.


add_action('init', 'cptui_register_my_cpt_slider');
function cptui_register_my_cpt_slider() {
register_post_type('slider', array(
'label' => 'Home Sliders',
'description' => '',
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'capability_type' => 'post',
'map_meta_cap' => true,
'hierarchical' => false,
'rewrite' => array('slug' => 'slider', 'with_front' => true),
'query_var' => true,
'supports' => array('title','editor','excerpt','trackbacks','custom-fields','comments','revisions','thumbnail','author','page-attributes','post-formats'),
'labels' => array (
'name' => 'Home Sliders',
'singular_name' => 'Slider',
'menu_name' => 'Home Sliders',
'add_new' => 'Add Slider',
'add_new_item' => 'Add New Slider',
'edit' => 'Edit',
'edit_item' => 'Edit Slider',
'new_item' => 'New Slider',
'view' => 'View Slider',
'view_item' => 'View Slider',
'search_items' => 'Search Home Sliders',
'not_found' => 'No Home Sliders Found',
'not_found_in_trash' => 'No Home Sliders Found in Trash',
'parent' => 'Parent Slider',
)
) ); }

After save functions.php then login wordpress admin you will see a option Home slider on left side navigation like Posts, Pages and you can add, edit or other things.

Now you want to display in front then use this code:


$args = array('post_type'=>'slider','posts_per_page' =>5, 'order'=>'ASC');
$banner = new WP_Query($args);
while($banner->have_posts()) : $banner->the_post();


if(has_post_thumbnail()): the_post_thumbnail('banner'); endif;

endwhile; wp_reset_postdata();

that’s it. Now as per your need you can customized the code, Like if you want to add testimonial then rename custom post type home slider to testimonial and also change on front code to display.

Disable og or open graph from wordpress yoast seo plugins

This is very common issue which is automatically displayed opengraph title, description, keywords etc. From this reason title, description, keywords become duplicate for seo views. so if you want to disable open graph from this plugin just you need to download wp-seo-main.php file from wordpress-seo plugins and line number 304 comment this code

$GLOBALS[‘wpseo_og’] = new WPSEO_OpenGraph;

That’s it.

Cheers! enjoy the code.

Add comment rating option on comment form in wordpress

comments

Normally in various wordpress projects we have to need add rating option on comment form so that user can see which post get more comments, ratings, votes etc. Recently I have implemented rating option on comment form in a project and display average ratings, total votes etc.

rating

add this code in your functions.php

You can also download all files code like single.php, category.php and functions.php files

Download code click Here


function format_comment($comment, $args, $depth) {
$GLOBALS['comment'] = $comment; ?>
<li id="li-comment-"> <img src="/img/no-photo.png" alt="">

printf(__('%s'), get_comment_author_link())

comment_approved == '0') : ?>
_e( 'Your comment is awaiting moderation.');
endif;
<!--Reply--> $depth, 'max_depth' => $args['max_depth']))) ?> Posted on:

comment_text(); ?>
<!--

Was this helpful? Yes! | No

-->

if ( ! comments_open() ) :

_e( 'Comments are closed.', 'twentyfourteen' );

endif;
}
function disable_comment_url($fields) {
unset($fields['url']);
return $fields;
}
add_filter('comment_form_default_fields','disable_comment_url');

For this, first you need install this plugins “Comment Rating Field Plugin”

then you add this code in your single.php inside your theme under while loop.



global $wpdb;
$postID = get_the_ID();
// Calculate average rating and total ratings
$results = $wpdb->get_results(" SELECT ".$wpdb->prefix."commentmeta.meta_value
FROM ".$wpdb->prefix."comments
LEFT JOIN ".$wpdb->prefix."commentmeta
ON ".$wpdb->prefix."comments.comment_ID = ".$wpdb->prefix."commentmeta.comment_id
WHERE ".$wpdb->prefix."comments.comment_post_ID = '".mysql_real_escape_string($postID)."'
AND ".$wpdb->prefix."comments.comment_approved = '1'
AND ".$wpdb->prefix."commentmeta.meta_key = 'crfp-rating'
AND ".$wpdb->prefix."commentmeta.meta_value != 0
GROUP BY ".$wpdb->prefix."commentmeta.comment_id");

$totalRatings = 0;
$averageRating = 0;
if (count($results) > 0) {
$totalRatings = count($results);
foreach ($results as $key=>$result) {
$totalRating += $result->meta_value;
}
$averageRating = (($totalRatings == 0 OR $totalRating == 0) ? 0 : round(($totalRating / $totalRatings), 0));
}

Average: echo $averageRating; ( echo $totalRatings; votes)
if($averageRating!='') : echo $ratingHTML = '

'; else : echo "No Rating"; endif;

comments_number( '0', '1', '%' ); Comments

Aslo display rating on user comments and on each posts on category page.

cmt

Comment if you have any confusion.

Cheers ! enjoy the code.

Display subcategories of specific parent category in dropdown

This is very simple which we need every time to display subcategories in drop down of specific parent category. And the solution is very simple you can use like this:

$args = array('child_of' => 17);
$categories = get_categories( $args );
foreach($categories as $category) {
echo '

Category: term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'

';
echo '

Description:'. $category->description . '

';
echo '

Post Count: '. $category->count . '

';
}

Here 17 is a parent category id and $category->term_id is the child category id and $category->name child category name of parent category which you can use in select html tag for drop down or as per your need.

Comments, If you have any confusion.

Cheers ! enjoy the code.

Custom field image resize or croping in wordpress as per need width and height

Today, I was working on a project and display the images using custom fields. But when upload big size images and check on site then the images was taking time to load so I have searched solutions from Google after struggle 4 hours, thanks god to solve my problem but I want to share this because its a very important for WordPress developer.Many times we need to call image using custom field instead set featured image.

The solution is very simple which I have mentioned below.

First download resize.docs file from here and copy the all code and paste on notepad or Dreamweaver and save resize.php.

Resize File

or direct from this Link:

Download Resize.php File

After that the file placed on your theme and call this file on your functions.php file.

Like

include_once('resize.php');

After that use this example:

$images = get_post_meta(get_the_ID(), 'wpcf-images');

$url = $images;
$width = 450; // Optional. Defaults to '150'
$height = 450; // Optional. Defaults to '150'
$crop = true; // Optional. Defaults to 'true'
$retina = false; // Optional. Defaults to 'false'
$img = matthewruddy_image_resize( $image, $width, $height, $crop, $retina );

For output resize image url you need place this in src like :

<img class="lazy-image" src=" echo $img['url']; ” />

If you have used plugins for custom fields for repeater for images for gallery or for other things to display images then use code like this:

while ( wpsc_have_products() ) : wpsc_the_product();


    $images = get_post_meta(get_the_ID(), 'wpcf-images'); // custom field to get values

    foreach ($images as $image) {
    $url = $image;
    $width = 450;
    $height = 450;
    $crop = true;
    $retina = false;
    $img = matthewruddy_image_resize( $image, $width, $height, $crop, $retina );

  • <img class="lazy-image" src=" echo $img['url']; ” />
  • }

endwhile;

The Error checking is simple as what you can see below.


if ( is_wp_error( $image ) ) {
echo $image->get_error_message() // Displays error message returned from resizing function
} else {
.. Do usual execution here .. // Everything appears to have gone well. Continue as normal!
}

Comments, if you have any question.

Cheers ! enjoy the code.

Display filesize after upload file in php

One day I need to display filesize after upload the file then I have searched on Google and get a function from manual but during max file upload it display error so its a simple define functions for max execution time and max filesize on top then this will work great.

Here is the code may be it can help for somebody.


@ini_set( 'upload_max_size' , '100M' );
@ini_set( 'post_max_size', '100M');
@ini_set( 'max_execution_time', '600' );

function display_filesize($filesize){

if(is_numeric($filesize)){
$decr = 1024; $step = 0;
$prefix = array('Byte','KB','MB','GB','TB','PB');

while(($filesize / $decr) > 0.9){
$filesize = $filesize / $decr;
$step++;
}
return round($filesize,2).' '.$prefix[$step];
} else {

return 'NaN';
}

}

Cheers ! enjoy the code.