Webstick.blog logo Wordpress, Design, SEO, Speed blog

Customize WordPress functions.php [2022] 💥

Customize WordPress functions.php

Every WordPress theme comes with a function.php file as default. This file is a type of plugin that allows you to do many cool things on your WordPress site. We will be sharing some of the best tricks to customize your WordPress functions.php. This file allows theme developers to define themes features and functions. This file functions just like a WordPress plugin. You can use it to add your custom code snippets to WordPress.


Advertisement

Divi


What's the difference between a site-specific WordPress plug-in and a functions.php file Which one is better?

A site-specific plugin, while faster and more convenient than the functions.php file, is much better. Because it doesn't depend on your WordPress theme, it will work with any theme. However, the functions file for a theme only works with that theme. If you want to change your theme, you will need to copy and paste the custom codes into your new theme. Here are some great tips about the WordPress functions file.

Remove WordPress version number

It is a good idea to use the most recent version of WordPress. You may want to delete the WordPress version number from you site. Add this code snippet in your functions file.


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

Add your own logo in your Wordpress

Administrator area for white-label WordPress. Your logo should be added first. Upload your logo to the theme's file folder as custom-logo.png. Your custom logo should measure 16x16 pixels This code can be then added to your theme's function 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;
}
</style>
';
}
//hook into the administrative header output
add_action('wp_before_admin_bar_render', 'wpb_custom_logo');

Wordpress Admin-panel: Modify footer

wordpress backend footer text


The WordPress admin area's footer displays "Thanks for using WordPress". You can change the message using this code.


function remove_footer_admin () {
 
echo 'Fueled by <a href="http://www.wordpress.org" target="_blank">WordPress</a>
 | WP Tutorials: <a href="https://www.webstick.blog" target="_blank">WP</a></p>';
 
}
 
add_filter('admin_footer_text', 'remove_footer_admin');

Add custom dashboard widgets in Wordpress

Most likely, you have seen widgets that allow you to add different themes and plugins to your WordPress dashboard. You can add one as a theme developer by copying 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 this custom blogtheme! Get in contact with the developer, <a href="mailto:[email protected]">klik hier</a>. Click for WordPress Tutorials: <a href="https://www.webstick.blog" target="_blank">Webstick</a></p>';
}	

Change default Gravatar in Wordpress

You may have seen the default mystery-man avatar on blogs. It is easy to replace the default mystery man avatar on blogs with one that represents your brand. Upload the image that you wish to be the default avatar, and then add the code to your function file.


add_filter( 'avatar_defaults', 'wpb_new_gravatar' );
function wpb_new_gravatar ($avatar_defaults) {
$myavatar = 'http://voorbeeld-site.nl/wp-content/uploads/2019/06/wpb-default-gravatar.png';
$avatar_defaults[$myavatar] = "Standaard Gravatar";
return $avatar_defaults;
}

Now you can go to the 'Settings' >> 'Discussion' page and select your default avatar.


Standard Wordpress gravatar


Dynamic copyright dates in your Wordpress footer

Editing the footer template of your theme can add the copyright date. It will not be visible when your site launches and it will not change automatically next year. This code can be used to add a dynamic copyright year to the WordPress footer.


function wpb_copyright() {
global $wpdb;
$copyright_dates = $wpdb->get_results("
SELECT
YEAR(min(post_date_gmt)) AS firstdate,
YEAR(max(post_date_gmt)) AS lastdate
FROM
$wpdb->posts
WHERE
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;
}                 

Once you have added this feature, go to your footer.php and insert the following code where you wish to display the dynamic copyright day:


<?php echo wpb_copyright(); ?>

This function looks for the date of the first and last messages. The function then echos the years whenever you mention the position.

Change your background color randomly in Wordpress

You can randomly change the background color of WordPress on every page load. This is how it's done. This code must be added to the functions.php file of your theme.


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)].
$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
echo $color;
}

Then you need to edit the header.php file in your Theme. Find the <body> -tag and replace it with following line:


<body <?php body_class(); ?> style="background-color:<?php wpb_bg();?>">>

Now you can save your changes and go to your website to see it in action.


Change Wordpress background color


Update WordPress-URLs

You need to update WordPress URLs if your WordPress login page is not loading or reloading frequently. You can do this by using the WP-config.php File. However, if you do this, you won't be able to change the address on the settings page. Site URL and WordPress URL fields cannot be edited. This can be fixed by adding this code to your function. You can also edit URLs in the database using MyPHPadmin.


update_option( 'siteurl', 'http://example-site.com' );
update_option( 'home', 'http://example-site.com' );

Do not forget to replace example-site.com with your domain name. Log in and go to Settings to set URLs. You will need to delete any code that you have added to your feature file. Otherwise, it will continue updating URLs each time you open your site.

Add additional image-sizes to Wordpress

WordPress automatically generates different formats for images when you upload them. Additional image sizes can be created for your theme. This code can be added to the function file of your theme.


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

This code creates three different image formats of different sizes. You can modify the code to suit your needs. This code allows you to display certain sizes of images anywhere on your theme.


<?php the_post_thumbnail( 'homepage-thumb' ); ?>

Add a new navigation menu(s) to your Theme

Wordpress lets theme developers create and display navigation menus. To add this code to your theme's function file, you can define a new location for your menu.


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 'Appearance' >> 'Menus' and you will see 'My Custom Menu' as a theme location option.


Wordpress extra menus


This code must be added to your theme, where you wish the navigation menu to appear.


<?php
wp_nav_menu( array( 
    'theme_location' => 'my-custom-menu', 
    'container_class' => 'custom-menu-class' ) ); 
?>

Add profile-fields for your authors

You want to add more fields to your WordPress author profiles? This code can be added to your functions file.


function wpb_new_contactmethods( $contactmethods ) {
// Add Twitter
$contactmethods['twitter'] = 'Twitter';
//add Facebook
$contactmethods['facebook'] = 'Facebook';
 
return $contactmethods;
}
add_filter('user_contactmethods','wpb_new_contactmethods',10,1);

This code will add Twitter & Facebook fields to user-profiles in Wordpress.

additional fields user profiles WP

These fields can now be displayed in your author template like the following:


<?php echo $curauth->twitter; ?>

You can add ready-made widget areas and sidebars to WordPress themes

Premium themes make it much easier to create sidebars. This one is very popular and many developers know it. It is a great tool and deserves to be included on the list. Copy the following code to 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' );

Proceed going to 'Appearance' » 'Widgets' in the back-end and you will see your newly made custom widget area.


new widgets in the back end


This code will display the widget area or sidebar of your theme.


<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('custom_sidebar') ) : ?>
<!–Default sidebar info goes here–>
<?php endif; ?>

Hide Wordpress login errors

Hackers can use Wordpress login errors to figure out if someone has entered the wrong password or username. You can make your WordPress login area more secure by hiding login errors.


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

Users will now see a standard message if they type an incorrect username/password.


no login hints wordpress


Schakel inloggen in WordPress met e-mailadres uit

Wordpress allows users to log into the site with either a username or an email address. This code can be added to your functions.php to disable email login.


remove_filter( 'authenticate', 'wp_authenticate_email_password', 20 );

Disable search in Wordpress

This code can be added to your function file to disable search functionality on WordPress sites.


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;" ) );

You can change the 'read more' text to access excerpts in WordPress

Do you wish to modify the text after the excerpt? This code can be added to the functions.php file of your theme.


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

RSS feeds are not required by all websites. This code can be added to the function file of your WordPress theme to disable RSS feeds.


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 restricts the length of an excerpt to 55 words. This code can be added to your functions file to alter the excerpt length. You can change the 100 number to indicate how many words you would like to appear in the extracts.


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

Add an admin user in Wordpress

You can create an administrator if you forget your WordPress password or email address. This code can be added to your theme's functions.php via an FTP client, hosting panel, or by entering this code directly into your theme.


function wpb_admin_account(){
$user = 'Username';
$pass = 'Password';
$email = '[email protected]';
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' );
} }
add_action('init','wpb_admin_account');

Remember to enter your username, password, and email. Don't forget to delete your code from your functions folder after you log in to your WordPress site.

Remove Welcome Panel from your Wordpress Dashboard


Remove Welcome Panel from WordPress Dashboard


The Wordpress admin area dashboard now has a welcome screen. This screen provides helpful shortcuts for new WordPress users to get things done. It can be easily hidden by adding the code below into your functions file.


remove_action('welcome_panel', 'wp_welcome_panel');

Showing total number of registered users in Wordpress

You would like to show the number of registered users for your WordPress site. This code can be added to the functions.php of your theme.


// 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 will generate a shortcode which will allow you display the total number registered users on your website. This shortcode can be added to [user_count] any page or post where you wish to display the total number.

Enable Shortcodes in text widgets

WordPress doesn't allow shortcodes to be used in text widgets by default. This can be fixed by adding this code to the function file of your theme.


// Allow shortcodes in text widgets
add_filter('widget_text','do_shortcode');

WordPress posts can be customized with CSS classes for even and odd.

There are many WordPress themes that have a class or odd theme for WordPress comments. This helps users to see where one comment ends and the next begins. The same technique can be used for WordPress posts. It is visually appealing and allows users to quickly scan pages with a lot of content. This code can be added to the functions.php file of your theme.


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 gives WordPress posts an unusual or even more classy look. To style your posts differently, you can add custom CSS. This is a sample code that will help you get started.


.even {
background:#f0f8ff;  
} 
.odd {
 background:#f4f4fb;
}

The result will be like this.


even and odd background colors wordpress messages


Add additional file-types to upload in Wordpress

WordPress defaults to allowing you to upload only the most common file types. You can however extend the functionality to allow you to upload other file types. This code can be added to the function file of your theme:


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 upload SVG or PSD files to WordPress. It's best to search it first to determine the file types that are allowed. Then, you can use these types in your code.

Remove default image-links in Wordpress

WordPress will automatically link an image to its attachment page or image file when you upload it. Users can click on an image to be taken to a different page than your post. How to stop WordPress automatically linking image files? This code snippet can be added to your function 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);

If you upload a new photo in WordPress, it won't be automatically linked. If you want, you can link it to the attachment or file page.


Wordpress image unlinked


Add an author infobox in WordPress posts

This method can be used to display author bios at end of posts on multi-author sites. Add this code to your functions.


function wpb_author_info_box( $content ) {
 
global $post;
 
// Find out if the post is one-post with a post author
if ( is_single() && isset( $post->post_author ) ) {
 
// Find the name of the author
$display_name = get_the_author_meta( 'display_name', $post->post_author );
 
// Display name not available? Use nickname
if ( empty( $display_name ) )
$display_name = get_the_author_meta( 'nickname', $post->post_author );
 
// Find the biographical information and description of the author
$user_description = get_the_author_meta( 'user_description', $post->post_author );
 
// Find author's URL
$user_website = get_the_author_meta('url', $post->post_author);
 
// The link to the author archive page is available
$user_posts = get_author_posts_url( get_the_author_meta( 'ID' , $post->post_author));
  
if ( ! empty( $display_name ) )
 
$author_details = '<p class="author_name">About ' . $display_name . '</p>';
 
if ( ! empty( $user_description ) )
// Auteur avatar and bio
 
$author_details .= '<p class="author_details">' . get_avatar( get_the_author_meta('user_email') , 90 ) . nl2br( $user_description ). '</p>';
 
$author_details .= '<p class="author_links"><a href="'. $user_posts .'">Bekijk alle berichten van ' . $display_name . '</a>';  
 
// Verify if the author has a website.
if ( ! empty( $user_website ) ) {
 
// Link to author's website
$author_details .= ' | <a href="' . $user_website .'" target="_blank" rel="nofollow">Website</a></p>';
 
} else { 
// If there isn't an author's website, close the paragraph
$author_details .= '</p>';
}
 
// All this information should be passed to the message content
$content = $content . '<footer class="author_bio_section" >' . $author_details . '</footer>';
}
return $content;
}
 
// Add feature to your post content filter
add_action( 'the_content', 'wpb_author_info_box' );
 
// Permit HTML in author's bio section
remove_filter('pre_user_description', 'wp_filter_kses');

To make it look better, you will need to add custom CSS. This sample CSS can be used as a guide.


.author_bio_section{
background: none repeat scroll 0 0 #F5F5F5;
padding: 15px;
border: 1px solid #ccc;
}
 
.author_name{
font-size:16px;
font-weight: bold;
}
 
.author_details img {
border: 1px solid #D8D8D8;
border-radius: 50%;
float: left;
margin: 0 10px 10px 0;
}

Disable XML-RPC in Wordpress

XML-RPC allows external apps to communicate remotely with your WordPress site. Hackers can exploit this vulnerability to attack security. To disable XMLRPC in WordPress, simply add the following code to your functions file:


add_filter('xmlrpc_enabled', '__return_false');




Divi



Scroll up