10 Useful Custom Functions For WordPress Themes
One of the most important and essential file in WordPress Theme is a file name called [highlight color="" bgcolor="#FFFBCC"]functions.php[/highlight]
. This file is useful for adding custom functions and filter to overwrite the WordPress core functions or adding new functions that didn’t exist in the core function.
In this article, I will share some useful custom functions you can add to your WordPress theme [highlight color="" bgcolor="#FFFBCC"]functions.php[/highlight]
file.
[notice type=”info”]Please note: some of the custom functions were collected from other sources which are not originally mine[/notice]
1. Add Browser Detection in <body> class
Here’s a snippet PHP code you can add into your functions.php to add a browser body class in your WordPress Theme.
[php]
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;
[/php]
Requirement
Your WordPress Theme must have below code in <body> for this to work.
[php]<body <?php body_class(); ?>>[/php]
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
[php]<body class="chrome">[/php]
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)
[php]body.ie div.my-container { width: auto; height:auto; }
body.gecko div.my-container { width: auto; height:auto; }[/php]
for me, i used the body.safari to change the ugly Helvetica fonts showing in the safari browser.
[php]/* default – body { font-family: helvetica, arial; } //lets use arial for safari browser */
body.safari { font-family: arial, sans-serif; }[/php]
2. Disable Adminbar for Normal Users
Sometimes when you are running a membership site, you prefer not to show the admin bar for the logged-in users but on the other hand, you want the admins and moderator to be able to use the admin bar, here’s a snippet of PHP code you can add into your WordPress theme functions.php.
[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’);
}[/php]
End Results
Now users that had the ability to ‘manage_options’ and ‘edit_posts’ [highlight color=”#888″ bgcolor=”#eee”](mostly admin and editor will have this priviliage)[/highlight] will had the adminbar when they logged in.
3. Post Thumbnail Check for Posts
Using or saving featured post thumbnail to each post had been a regularity for blog writers but in some cases, you want to apply a CSS class to a post that does not have a post-thumbnail attached to posts. Here’s a PHP snippet you can use.
[php]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;[/php]
Requirement
Your WordPress theme must have the below code for this to work.
[php]<?php post_class(); ?>[/php]
End Results
Now your WordPress Theme will detect if your posts have a thumbnail attached or not.
[php]/* if have thumbnail – <article <?php post_class(); ?>>*/
<article class="has_thumb post post-99">[/php]
[php]/* if do not have thumbnail */
<article class="has_no_thumb post post-99">[/php]
4. Add Custom Field to Profile
Need to add more options for the user profiles, try adding this to functions.php
[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;[/php]
End Results
Now if you navigate to wp-admin/profile.php, you will see extra boxes to enter your Twitter, Facebook, and Google Plus profile links.
How to use the code?
You can simply add this code inside author.php
[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 ?>[/php]
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.
[php]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;[/php]
After adding the above code to functions.php, you need to open [highlight color=”” bgcolor=”#eee”]single.php[/highlight] or [highlight color=”” bgcolor=”#eee”]single-TAXONOMY.php[/highlight] and add this code to before end of <?php endwhile; ?>
like this
[php]<?php set_wp_post_view( get_the_ID() ); ?>
<?php endwhile; ?>[/php]
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]<?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>[/php]
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.
[php]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;
}[/php]
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
[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’);[/php]
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
[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;[/php]
9. Remove WordPress Updates Notification
If you need to remove the annoying yellow box notification of WordPress Updates, simply add this code to your functions.php
[php]function remove_upgrade_nag() {
echo ‘<style type="text/css">
.update-nag {display: none}
</style>’;
}
add_action(‘admin_head’, ‘remove_upgrade_nag’);[/php]
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.
[php]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;
}
}[/php]
so instead of using
[php]<?php the_category(‘, ‘); ?>[/php]
You can use
[php]<?php echo get_singular_cat(); ?>[/php]
End Results
[php]
/* if use the_category() */
Category: jobs, media, news, game and feature
/* if use get_singular_cat() */
Category: jobs
[/php]
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 another developer:
çok yararlı bilgiler.Teşekkürler{thank you}
Thank you, very nice and helpful information
been looking for no4.add custom profile, thanks
Hi,
I pasted that first codes Twitter,facebook,google in the functions.php and it works great! It shown on the buddypress activity page.
Then I pulled the arthur.php from the parent and pasted that other codes in the arthur.php before .
I want to upload in the child-theme directory so it wouldn’t overwritten when I update the theme.
I uploaded just about every folders in the child-theme, not showing, no luck? Can you tell me which directory I should upload to?
Please advise help, Thanks
it should be in child theme functions.php
Hi Admin,
Those codes in the functions.php works great 🙂
But those 6 lines of codes below, I don’t think this go in the functions.php
This are the 6 lines below
How to use the code?
You can simple add this code inside author.php
I pasted this 6 lines before (?php endwhile; ?) in the arthur.php, I even uploaded it back in the parent directory to see, no luck neither?
Any other advise? Thanks
it works to me, its in author.php, add below code before
[php]<?php if( have_posts() ): ?>[/php]
add below code:
[php]<?php if(isset($_GET[‘author_name’])) :
$curauth = get_userdatabylogin($author_name);
else :
$curauth = get_userdata(intval($author));
endif; ?>
<?php
echo ‘<a href="’. $curauth->twitter . ‘">’. $author_name . "’s" . ‘ Twitter</a>’ . ‘ ’;
echo ‘<a href="’. $curauth->facebook . ‘">’. $author_name . "’s" . ‘ Facebook</a>’ . ‘ ’;
echo ‘<a href="’. $curauth->google_plus . ‘">’. $author_name . "’s" . ‘ Google Plus</a>’;
?>[/php]
no need to loop the author meta, just display them at top of author page.
Hi Admin,
I tried everything to put this codes to show on user profile. Still no luck at all? Maybe it doesn’t work for my theme or buddypress in general.
I have no idea, but anywhere I can put this code besides the Arthur.php?
Any other solutions you can advise? Thanks,
this will not show in buddypress user profile, there should plugin that handle members’ social profile globally. this code might had been deprecated since its years ago.
remove this code if you intall one so it won’t duplicate the social profile functions.
Hi Admin,
I already removed it since is not working for the Arthur (profile).
However, that one for the functions works great! Thanks for helping.