10 Useful Custom Functions For WordPress Themes


88c8d wordpress functions 10 Useful Custom Functions For WordPress Themes

One of the most important and essential file in WordPress Theme is a file name called functions.php. This file is useful for adding custom functions and filter to overwrite the WordPress core functions or adding a new functions that wasn’t existed in core function.

In this article, i will share some useful custom functions you can add into your WordPress theme functions.php file.

1. Add Browser Detection in body class

Here’s snippet php code you can add into your functions.php to add a browser body class in your WordPress Theme.

if( !function_exists( 'get_browser_body_class' )):
////////////////////////////////////////////////////////////////////
// Browser Detect
///////////////////////////////////////////////////////////////////
function get_browser_body_class($classes) {
global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;
if($is_lynx) $classes[] = 'lynx';
elseif($is_gecko) $classes[] = 'gecko';
elseif($is_opera) $classes[] = 'opera';
elseif($is_NS4) $classes[] = 'ns4';
elseif($is_safari) $classes[] = 'safari';
elseif($is_chrome) $classes[] = 'chrome';
elseif($is_IE) $classes[] = 'ie';
else $classes[] = 'unknown';
if($is_iphone) $classes[] = 'iphone';
return $classes;
}
add_filter('body_class','get_browser_body_class');
endif;

Requirement
Your WordPress Theme must have below code in body for this to work.

body ?php body_class(); ?

End Results
Now your WordPress Theme will detect which browser your visitor using so if your visitors are using chrome. it will echo body class like this

body class="chrome"

What the functions can do?
You can add a primary css class for browser condition like if visitors are in internet explorer or mozilla firefox, you can add this to your stylesheet (style.css)

body.ie div.my-container { width: auto; height:auto; }
body.gecko div.my-container { width: auto; height:auto; }

for me, i used the body.safari to change the ugly helvetica fonts showing in safari browser.

/* default - body { font-family: helvetica, arial; } //lets use arial for safari browser */
body.safari { font-family: arial, sans-serif; }
2. Disable Adminbar for Normal Users

Sometime when you are running a membership site, you prefer not to show the adminbar for logged-in user but in the other hand you want the admins and moderator to be able to use the adminbar, here’s a snippet php code you can add into your wordpress theme functions.php.

// show admin bar only for admins
if (!current_user_can('manage_options')) {
	add_filter('show_admin_bar', '__return_false');
}
// show admin bar only for admins and editors
if (!current_user_can('edit_posts')) {
	add_filter('show_admin_bar', '__return_false');
}

End Results
Now users that had the ability to ‘manage_options’ and ‘edit_posts’ (mostly admin and editor will have this priviliage) will had the adminbar when they logged in.

3. Post Thumbnail Check for Posts

Using or saving featured post thumbnail to each posts had been a regularality for blog writers but in some cases you want to apply a css class to a post that do not have post thumbnail attached into posts. Here’s a php snippet you can use.

if( !function_exists( 'get_has_thumb_class' )):
////////////////////////////////////////////////////////////////////////////////
// Check if post has thumbnail attached
////////////////////////////////////////////////////////////////////////////////
function get_has_thumb_class($classes) {
global $post;

if(  has_post_thumbnail($post-ID) ) {
$classes[] = 'has_thumb';
} else {
$classes[] = 'has_no_thumb';
}

return $classes;
}
add_filter('post_class', 'get_has_thumb_class');
endif;

Requirement
Your WordPress Theme must have a below code for this to work.

?php post_class(); ?

End Results
Now your WordPress Theme will detect if your posts have a thumbnail attached or not.

/* if have thumbnail - article ?php post_class(); ?*/
article class="has_thumb post post-99"
/* if do not have thumbnail */
article class="has_no_thumb post post-99"
4. Add Custom Field to Profile

Need to add more options for the user profiles, try adding this to functions.php

if( !function_exists( 'wp_add_new_profile_meta' )):
////////////////////////////////////////////////////////////////////////////////
// Add new profile meta
////////////////////////////////////////////////////////////////////////////////
function wp_add_new_profile_meta( $contactmethods ) {
// Add Twitter
$contactmethods['twitter'] = 'Twitter';
//add Facebook
$contactmethods['facebook'] = 'Facebook';
//add Goolge+ Profile link
$contactmethods['google_plus'] = 'Google Plus';

return $contactmethods;
}
add_filter('user_contactmethods','wp_add_new_profile_meta',10,1);
endif;

End Results
Now if you navigate to wp-admin/profile.php, you will see an extra boxes to enter your Twitter, Facebook and Google Plus profile links.

88c8d profile custom meta 10 Useful Custom Functions For WordPress Themes

How to use the code?
You can simple add this code inside author.php

?php if(isset($_GET['author_name'])) :
$curauth = get_userdatabylogin($author_name);
else :
$curauth = get_userdata(intval($author));
endif; ?
?php echo $curauth-twitter; //twitter, facebook or google_plus ?
5. Add Post View Counter

If you want to build up popular posts, you can add this code to your functions.php. This code will collect how many times the posts had been viewed and save it on each post post view meta key and meta value.

if( !function_exists('get_wp_post_view') ) :
////////////////////////////////////////////////////////////////////////////////
// get post view count
////////////////////////////////////////////////////////////////////////////////
function get_wp_post_view($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0";
    }
    return $count;
}
function set_wp_post_view($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}
endif;

After adding the above code to functions.php, you need to open single.php or single-TAXONOMY.php and add this code to before end of ?php endwhile; ? like this

?php set_wp_post_view( get_the_ID() ); ?
?php endwhile; ?

How To Get The Most Viewed Posts?
If you need to get the most viewed posts, just add this to anywhere in your themes.

?php
$my_query = new WP_Query( array(  'post_type'= 'post', 'meta_key' = 'post_views_count', 'orderby' = 'meta_value_num', 'order' = 'DESC','posts_per_page' = 10 ) );
?
ul class="most-viewed"
?php while ($my_query-have_posts()) : $my_query-the_post(); ?
li
a title="?php echo the_title(); ?" href="?php echo get_permalink( get_the_ID() ); ?"?php echo the_title(); ?/a - small
?php echo get_post_meta( get_the_ID() , 'post_views_count', true);; ? Viewed/small
/li
?php endwhile; wp_reset_query(); ?
/ul
6. Add class to first post in the loop

If you wanted to add emphasis to the first post in your blog adding this snippet to the functions.php of your wordpress theme will add the class of “first” to your first post.

add_filter( 'post_class', 'wps_first_post_class' );
function wps_first_post_class( $classes ) {
    global $wp_query;
    if( 0 == $wp_query-current_post )
        $classes[] = 'first';
        return $classes;
}
7. Only Login User Allowed To View Site

if you wanted only login users to view the site. Add this code to your functions.php

function wp_login_access_only() {
if( !is_user_logged_in() ) {
wp_redirect( site_url('/wp-login.php') );
}
}
add_filter('get_header', 'wp_login_access_only');
8. Remove Page From Search Filter

If you want to filter out pages when users use searchform to search your posts, add this code snippet into your functions.php

if( !function_exists( 'remove_page_search_filter' )):
function remove_page_search_filter($query) {
if ($query-is_search) {
$query-set('post_type', 'post');
}
return $query;
}
add_filter('pre_get_posts','remove_page_search_filter');
endif;
9. Remove WordPress Updates Notification

If you need to remove the annoying yellow box notification of WordPress Updates, simple add this code to your functions.php

function remove_upgrade_nag() {
   echo 'style type="text/css"
           .update-nag {display: none}
         /style';
}
add_action('admin_head', 'remove_upgrade_nag');
10. Show single category only in posts

If you’re designing a magazine grid WordPress Theme, sometime a posts with 3-4 category could break the layout in grid system theme so here’s a php snippet you can add into functions.php to retrieve only 1 main category only for each post.

if( !function_exists('get_singular_cat') ) {
////////////////////////////////////////////////////////////////////////////////
// get/show single category only
////////////////////////////////////////////////////////////////////////////////
function get_singular_cat() {
global $post;
$category = get_the_category();
if ($category) {
$single_cat = 'a href="' . get_category_link( $category[0]-term_id ) . '" title="' . sprintf( __( "View all posts in %s", TEMPLATE_DOMAIN ), $category[0]-name ) . '" ' . '' . $category[0]-name.'/a';
}
return $single_cat;
}
}

so instead of using

?php the_category(', '); ?

You can use

?php echo get_singular_cat(); ?

End Results

/* if use the_category() */
Category: jobs, media, news, game and feature
 /* if use get_singular_cat() */
Category: jobs
Final Conclusion

Custom functions can be very useful when creating your new WordPress Theme. These are just among many custom functions you can found from other developer:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>