WordPress Functions File

What is the Function File in WordPress?

All WordPress themes come with a powerful "functions.php" file. This file acts as a plugin and allows you to do a lot of interesting things on your WordPress site. In this article, we will show you some of the most useful tricks for your WordPress functions file

Change some of the default behaviors of WordPress by using the "functions.php" file. Adding features and functionality to any WordPress Website with PHP code. You can use it to call native PHP functions, WordPress functions, or to define your own functions

There are a few differences between using a "plugin" and a "functions.php" file
A WordPress Plug-in: Executes only when individually activated via the Plugins panel. Applies to all themes. Requires specific unique Header text. Is stored in wp-content/plugins, usually in a subdirectory
A functions file: Executes only when in the currently activated theme's directory. Applies only to that theme. If the Theme is changed, the functionality is unused. Requires no unique Header text. Is stored with each Theme in the Theme's subdirectory in wp-content/themes

Each Theme has its own functions file, but only the functions.php with the "Active" Theme affects how your Website will publicly display. If your theme already has a functions file, you can add the below snippets to it. If not, you can create a plain-text file named functions.php to add to your theme's directory

Adding a Favicon to your WordPress Site

This code makes it easy. Create your favicon and upload to site’s root directory. Change the "image" directory if needed. Also be sure that the wp_head is present within your theme’s header.php file. Add the following code in your functions.php file makes it so by adding the required line to your <head> area:

// add a favicon to your function blog_favicon()
{ echo '<link rel="Shortcut Icon" type="/image/x-icon" href="'.get_bloginfo('wpurl').'/favicon.ico" />'; }
add_action('wp_head', 'blog_favicon');');

Changing Footer in WordPress Admin Panel

The footer in WordPress Admin area shows the message "Thank you for creating with WordPress". You can change the text and links to anything you want by adding this code

function remove_footer_admin () {
echo 'Powered by <a href="https://www.wordpress.org" target="_blank">WordPress</a>
| WordPress Tutorials: <a href="https://www.wpbeginner.com" target="_blank">WPBeginner</a></p>';
add_filter('admin_footer_text', 'remove_footer_admin');

Have a different Favicon for the Admin Area

Add a unique favicon to your Admin pages. Create a favicon and upload to your Theme’s "/images/" directory. Then add this code: Change the image directory to whatever is needed

// add a favicon for your admin function admin_favicon()
{ echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.get_bloginfo('stylesheet_directory').'/images/favicon.png">'; }
add_action(‘admin_head’, ‘admin_favicon’);

blogs on hosting

Changing the Default Gravatar in WordPress

Tired of seeing the same "default" Avatar on your blogs? Replace it with your own branded custom avatars. Simply upload the image you want to use as default avatar and then add this code to your functions file

add_filter( 'avatar_defaults', 'wpb_new_gravatar' );
function wpb_new_gravatar ($avatar_defaults) {
$myavatar = 'http://Your-Domain.com/wp-content/uploads/2017/01/wpb-default-gravatar.png';
$avatar_defaults[$myavatar] = "Default Gravatar";
return $avatar_defaults;
Head to the "Settings" » "Discussion" page and select your default avatar

Remove WordPress Version Numbers

For security reasons you should always update to the latest version of WordPress. But if you want to remove the WordPress version number from your Website. Simply add this code to your functions file

function wpb_remove_version()
{ return ''; }
add_filter('the_generator', 'wpb_remove_version');

Add a Custom Dashboard Logo

Want to change your WordPress Admin area? Upload your custom logo to your "Theme’s" images folder as custom-logo.png. Make sure your custom logo is 16×16 pixels in size. Add this code to your theme’s functions file

function wpb_custom_logo() {
echo '
<style type="text/css">
#wpadminbar #wp-admin-bar-wp-logo > .ab-item .ab-icon:before {
background-image: url(' . get_bloginfo('stylesheet_directory') . '/images/custom-logo.png) !important;
background-position: 0 0;
color:rgba(0, 0, 0, 0);
#wpadminbar #wp-admin-bar-wp-logo.hover > .ab-item .ab-icon {
background-position: 0 0;
//hook into the administrative header output
add_action('wp_before_admin_bar_render', 'wpb_custom_logo');

Add Custom Dashboard Widgets in WordPress

You can add whatever widget you want to your WordPress dashboard, simply by adding the following code:

add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');
function my_custom_dashboard_widgets() {
global $wp_meta_boxes;
wp_add_dashboard_widget('custom_help_widget', 'Theme Support', 'custom_dashboard_help');
function custom_dashboard_help() {
echo '<p>Welcome to Custom Blog Theme! Need help? Contact the developer <a href="mailto:yourusername@gmail.com">here</a>. For WordPress Tutorials visit: <a href="https://www.wpbeginner.com" target="_blank">WPBeginner</a></p>';

Dynamic Copyright Date in WordPress Footer

You can add copyright date by editing the footer template in your theme. However, it will not show when your site started and it will not automatically change next year. Use this code to add a dynamic copyright date in WordPress footer

function wpb_copyright() {
global $wpdb;
$copyright_dates = $wpdb->get_results("
YEAR(min(post_date_gmt)) AS firstdate,
YEAR(max(post_date_gmt)) AS lastdate
post_status = 'publish'
$output = '';
if($copyright_dates) {
$copyright = "© " . $copyright_dates[0]->firstdate;
if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate) {
$copyright .= '-' . $copyright_dates[0]->lastdate;
$output = $copyright;
return $output;
After adding this code, you will need to open your footer.php file and add the following code wherever you like to display the dynamic copyright date:
<?php echo wpb_copyright(); ?>
This function looks for the date of your first post, and the date of your last post. It then shows the years wherever you call the function

Randomly Change the Background Color in WordPress

Randomly change the background color on your WordPress site with each visit and page reload. First add this code to your theme’s functions file

function wpb_bg() {
$rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
$color ='#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].
echo $color;
You will need to edit the header.php file in your theme. Locate the <body> tag and add replace it with this line:
<body <?php body_class(); ?> style="background-color:<?php wpb_bg();?>">>

Update your WordPress URLs

If your WordPress login page keeps refreshing or you are unable to access the Admin area. You need to update WordPress URLs. One way to do this is by using wp-config.php file. However, if you do that you will not be able to set the correct address on the settings page. The WordPress URL and Site URL fields will be locked and uneditable. If you want to fix this, then you should add this code to your functions file. replace example.com with your own domain name

update_option( 'siteurl', 'https://example.com' );
update_option( 'home', 'https://example.com' );
Go to Settings and set the URLs there. After that you should remove the code you added to the functions file, otherwise it will keep updating those URLs any time your site is accessed

Add Additional Image Sizes in WordPress

WordPress automatically creates several image sizes when you upload an image. You can also create additional sizes to use in your Themes. This code creates three new image with different sizes. Change the code to meet your own requirements. You can display an image size anywhere in your theme using this code

add_image_size( 'sidebar-thumb', 120, 120, true ); // Hard Crop Mode
add_image_size( 'homepage-thumb', 220, 180 ); // Soft Crop Mode
add_image_size( 'singlepost-thumb', 590, 9999 ); // Unlimited Height Mode

Add New Navigation Menus to Your Theme

WordPress allows Developers to define navigation menus and then display them. Add this code in your theme’s functions file to define a new menu location in your theme

function wpb_custom_new_menu()
{ register_nav_menu('my-custom-menu',__( 'My Custom Menu' )); }
add_action( 'init', 'wpb_custom_new_menu' );
You can now go to the "Appearance" » "Menus" and you will see "My Custom Menu" as theme location option
You will need to add this code to your theme where you want to display navigation menu
wp_nav_menu( array(
'theme_location' => 'my-custom-menu',
'container_class' => 'custom-menu-class' ) );

Add Author Profile Fields

Add extra fields to your "Author Profiles" in WordPress. As an example this code will add Twitter and Facebook fields to user profiles in WordPress, Change to suit your needs

function wpb_new_contactmethods( $contactmethods ) {
// Add Twitter
$contactmethods['twitter'] = 'Twitter';
//add Facebook
$contactmethods['facebook'] = 'Facebook';
return $contactmethods;
Display these fields in your "Author Template" like this:
<?php echo $curauth->twitter; ?>

Adding "Widget Ready" Areas or Sidebar in WordPress Themes

This is one of the most used and many WordPress developers already know about this. For those who don’t know just paste the following code in your functions.php file:

// Register Sidebars
function custom_sidebars() {
$args = array(
'id' => 'custom_sidebar',
'name' => __( 'Custom Widget Area', 'text_domain' ),
'description' => __( 'A custom widget area', 'text_domain' ),
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
register_sidebar( $args );
add_action( 'widgets_init', 'custom_sidebars' );
Go to "Appearance" » "Widgets" page and you will see your new custom widget area
To display this sidebar or widget ready area in your theme add this code:
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('custom_sidebar') ) : ?>
<!–Default sidebar info goes here–>
<?php endif; ?>

Manipulate RSS Feed Footer

Have you seen websites that shows their advertisement in their RSS Feeds below each post. You can accomplish this with a simple function:

function wpbeginner_postrss($content) {
$content = 'This post was written by Syed Balkhi '.$content.'Check out WPBeginner';
return $content;
add_filter('the_excerpt_rss', 'wpbeginner_postrss');
add_filter('the_content', 'wpbeginner_postrss');

Add Featured Images to RSS Feeds

The "Post" thumbnail or "Featured Image" are usually only displayed within your Website design. You can extend that functionality to your RSS feed with this function in your RSS feed

function rss_post_thumbnail($content) {
global $post;
if(has_post_thumbnail($post->ID)) {
$content = '<p>' . get_the_post_thumbnail($post->ID) .
'</p>' . get_the_content();
return $content;
add_filter('the_excerpt_rss', 'rss_post_thumbnail');
add_filter('the_content_feed', 'rss_post_thumbnail');

Hide Login Errors in WordPress

Login errors could be used by Hackers to see if they entered a wrong user-name or password. By hiding these login errors you can make your login area a bit more secure. Users will now see a generic "Something is wrong!" message when they enter incorrect user-name or password. Change the message to what ever you like

function no_wordpress_errors(){
return 'Something is wrong!';
add_filter( 'login_errors', 'no_wordpress_errors' );

Disable Login by Email in WordPress

WordPress allows users to login with username or email address. You can disable the "Login by Email" by adding this code to your functions file

function fb_filter_query( $query, $error = true ) {
if ( is_search() ) {
$query->is_search = false;
$query->query_vars[s] = false;
$query->query[s] = false;
// to error
if ( $error == true )
$query->is_404 = true;
add_action( 'parse_query', 'fb_filter_query' );
add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

Remove Default Image Links in WordPress

By default, when you upload an image in WordPress it automatically links to the image file or the attachment page. If users click on the new image they are then taken to a new page away from your post. Stop WordPress from automatically linking image uploads by adding this code snippet to your functions file:

function wpb_imagelink_setup() {
$image_set = get_option( 'image_default_link_type' );
if ($image_set !== 'none') {
update_option('image_default_link_type', 'none');
add_action('admin_init', 'wpb_imagelink_setup', 10);

Delay Posts in RSS Feed

Sometimes you may need to edit your articles before they go live and is distributed to your RSS feed and or email subscribers. In this code we set it to 10 minutes as a "$wait or delay time". Feel free to change that into any number of minutes you want

function publish_later_on_feed($where) {
global $wpdb;
if ( is_feed() ) {
// timestamp in WP-format
$now = gmdate('Y-m-d H:i:s');
// value for wait; + device
$wait = '10'; // integer
// http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff
// add SQL-sytax to default $where
$where .= " AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, '$now') > $wait ";
return $where;
add_filter('posts_where', 'publish_later_on_feed');

Change Read More Text for Excerpts in WordPress

Change the text that appears after a "Excerpt". Simply add this code to your theme’s functions file

function modify_read_more_link() {
return '<a class="more-link" href="' . get_permalink() . '">Your Read More Link Text</a>';
add_filter( 'the_content_more_link', 'modify_read_more_link' );

Disable RSS Feeds in WordPress

If you would like to disable RSS feeds on your WordPress website add this code to your theme’s functions file

function fb_disable_feed() {
wp_die( __('No feed available,please visit our <a href="'. get_bloginfo('url') .'">homepage</a>!') );
add_action('do_feed', 'fb_disable_feed', 1);
add_action('do_feed_rdf', 'fb_disable_feed', 1);
add_action('do_feed_rss', 'fb_disable_feed', 1);
add_action('do_feed_rss2', 'fb_disable_feed', 1);
add_action('do_feed_atom', 'fb_disable_feed', 1);

Change Excerpt Length in WordPress

WordPress limits excerpt word lengths to 55. If you would like to change that add this code to your functions file. Change 200 to the number of words you want to show in the excerpts

function new_excerpt_length($length) {
return 200;
add_filter('excerpt_length', 'new_excerpt_length');

Add a "Temporary Admin User" in WordPress

Lost or forgotten your WordPress username, password and or email? You can add an "Admin Temporary User" by adding this code to your theme’s functions file by using an FTP client and simple text editor
Change the "Username", "Password", and "Email" fields to yours

function wpb_admin_account(){
$user = 'Username';
$pass = 'Password';
$email = 'email@domain.com';
if ( !username_exists( $user ) && !email_exists( $email ) ) {
$user_id = wp_create_user( $user, $pass, $email );
$user = new WP_User( $user_id );
$user->set_role( 'administrator' );
} }
https://soliloquywp.com/beginners-guide-to-add-custom-image-sizes-in-wordpress/ add_action('init','wpb_admin_account');
Once you login to your WordPress site, do not forget to delete the code from your functions file

Remove Welcome Panel from WordPress Dashboard

The "Welcome Panel" is a meta box added to the dashboard screen of your Admin area. It provides useful shortcuts for beginners to do things on their new WordPress site. You can easily hide this by adding the below code in your functions file

remove_action('welcome_panel', 'wp_welcome_panel');

Show Total Number of Registered Users in WordPress

Do you want to show total number of registered users on your WordPress site? You need to add the following code to your theme’s functions.php file or a site specific plugin. Add this shortcode to your post or page where you want to show the total number of users

// Function to return user count
function wpb_user_count() {
$usercount = count_users();
$result = $usercount['total_users'];
return $result;
// Creating a shortcode to display user count
add_shortcode('user_count', 'wpb_user_count');
This code creates shortcode [user_count] which you can use in your WordPress posts, pages, or a sidebar widget to display the user count. The function does not add any HTML formatting to the user count and simply returns the number. You may want to wrap the shortcode around HTML to use CSS or basic HTML formatting. For example:
<p>Join <strong>[user_count]</strong> other users who share your interest:</p>

Exclude Specific Categories from RSS Feed

Do you want to exclude specific categories from your WordPress RSS feed? Add this code to your theme’s functions file

function exclude_category($query) {
if ( $query->is_feed ) {
$query->set('cat', '-5, -2, -3');
return $query;
add_filter('pre_get_posts', 'exclude_category');

Enable Shortcode Execution in Text Widgets

By default, WordPress does not execute shortcodes inside text widgets. To fix this you need to simply add this code to your theme’s functions file

// Enable shortcodes in text widgets

Add Odd and Even CSS Classes to WordPress Posts

You may have seen WordPress themes using an old or even class for WordPress comments. It helps users visualize where one comment ends and the next one begins. You can use the same technique for your WordPress posts. It looks aesthetically pleasing and helps users quickly scan large pages. Simply add this code to your theme’s functions file

function oddeven_post_class ( $classes ) {
global $current_class;
$classes[] = $current_class;
$current_class = ($current_class == 'odd') ? 'even' : 'odd';
return $classes;
add_filter ( 'post_class' , 'oddeven_post_class' );
global $current_class;
$current_class = 'odd';
This code simply adds an odd or even class to WordPress posts. You can now add custom CSS to style them differently. Here is a sample code to help you get started
.even {
.odd {

Add Additional File Types to be Uploaded in WordPress

By default, WordPress allows you to upload a limited number of most commonly used file types. However, you can extend it to allow other file types. Add this code to your theme’s functions file:

function my_myme_types($mime_types){
$mime_types['svg'] = 'image/svg+xml'; //Adding svg extension
$mime_types['psd'] = 'image/vnd.adobe.photoshop'; //Adding photoshop files
return $mime_types;
add_filter('upload_mimes', 'my_myme_types', 1, 1);
This code allows you to upload SVG and PSD files to WordPress. You will need to Google to find out the mime types for the file types you want to allow and then use it in the code

Add Feed Links to Header

WordPress can add all relevant feed links (main, comments, categories...) to your "<head>" area. This will check to see if you’re using a version of WordPress that is compatible, and then enable the automatic feed links. Add the following snippet to make it work:

if (function_exists('automatic_feed_links')) {
} else {

Automatic jQuery Inclusion

How to add jQuery by placing a little snippet from your theme’s functions.php file. This code ensures that only one copy of jQuery is included, and calls it from Google’s Servers. Note This function needs to be located before the threaded-comments function in order for it to work

if (!is_admin()) {
wp_register_script('jquery', ("https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"), false);

Enabling Threaded Comments

Enabling threaded comments just by adding a snippet of code into the functions.php file. Note This function needs to be located after the jQuery-inclusion function:

function enable_threaded_comments(){
if (!is_admin()) {
if (is_singular() AND comments_open() AND (get_option('thread_comments') == 1))
add_action('get_header', 'enable_threaded_comments');

Removing Unwanted Text from the Head Section

WordPress adds unnecessary text in the document <head>. Such as version numbers, WLW, RSD, and index links. To clean this up add this snippet into the functions.php template:

remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'start_post_rel_link', 10, 0);
remove_action('wp_head', 'parent_post_rel_link', 10, 0);
remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0);

Adding Google Analytics to the Footer

Add this code to the footer.php file. Note Replace the “UA-123456-1” with your actual GA code. There are three currently available Analytics options and modify the code accordingly. This code is using the newer “ga.js” tracking code, Changed to either of the other methods if using them

function add_google_analytics() {
echo '<script src="http://www.google-analytics.com/ga.js" type="text/javascript">'<script>';
echo '<script type="text/javascript">';
echo 'var pageTracker = _gat._getTracker("UA-XXXXX-X");';
echo 'pageTracker._trackPageview();';
echo '</script>';
add_action('wp_footer', 'add_google_analytics');

No More "Jumping" for the Read More link

One anoyoing thing that WordPress does is “Jump” the user to the location of the “<!--more-->” tag on the single-post-view when the “read more” link is clicked. If the jump was on the same page, yes. But to load a new page and then take the user halfway down the page? Add this function to stop the jumpingl:

function no_more_jumping($post) {
return '< a href="'.get_permalink($post->ID).'" class="read-more">'.'Continue Reading'.'< /a>';
add_filter('excerpt_more', 'no_more_jumping');
add_filter('the_content_more_link', 'remove_more_jump_link');

Custom Admin Login Logo

The WordPress logo that is branding your various login pages? Change that to whatever you like. Create a custom login image, name it “custom-login-logo.png”, and upload it to your theme’s /images/ directory. Then add this code:

function custom_login_logo() {
echo '<style type="text/css">
h1 a { background-image: url('.get_bloginfo('template_directory').'/images/custom-login-logo.png) !important; }
add_action('login_head', 'custom_login_logo');
Make sure that the path and image names match that of your setup. When creating your image keep in mind the properties of the original: 30px length, 31px height, transparent GIF format, and header background color of #464646

Disable Unused Widget Areas

A handy function for removing unwanted widget areas from your theme. Nice for customizing existing themes. Note If you only want to disable widgets on your Home page, then remove the two comment slashes (“//”) from the second line.

function disable_all_widgets($sidebars_widgets) {
//if (is_home())
$sidebars_widgets = array(false);
return $sidebars_widgets;
add_filter('sidebars_widgets', 'disable_all_widgets');

Stop the "WordPress Update Now"

This one is not for the average user. But if you really dislike the “Please update now..” message that appears on every page in the WordPress Admin when new versions are available? Add this code:

if (!current_user_can('edit_users')) {
add_action('init', create_function('$a', "remove_action('init', 'wp_version_check');"), 2);
add_filter('pre_option_update_core', create_function('$a', "return null;"));

Include category ID in body_class & post_class

By default, WordPress body_class and post_class do not include the ID of the category of the current post. This custom function will add it:

function category_id_class($classes) {
global $post;
foreach((get_the_category($post->ID)) as $category)
$classes [] = 'cat-' . $category->cat_ID . '-id';
return $classes;
add_filter('post_class', 'category_id_class');
add_filter('body_class', 'category_id_class');
-------------------------------------------- WordPress Tutorials

Comments, questions or leave a reply
Contact Us

Tweet  Share  Pin  Tumble  Email