Blog

  • Change Submit Button Text in WordPress Comment Form

    How to Change Submit Button Text in WordPress Comment Form

    Comment system is an integral part of WordPress and that’s why we are always looking for ways to customize WordPress comments. In earlier articles, we have already seen how to use circular shaped avatars, change reply link text in threaded comments, highlight post author comments and how to automatically link twitter username in comments. In this article I will show you how you can change submit button text in comment form instead of default “Post Comment”. For branding purposes or may be to spice up comment form, you might want to change the submit button text into something more interesting and unique.

    WordPress comment form is generated by a single WordPress function, that’s why it’s not as easy as it appears to change submit button text. So you are left with two options, either you can build comment form from scratch or you can use WordPress filters to alter function. To be honest, second option is a lot easier than first one and much better too.

    Just paste this code snippet below, in your theme’s functions.php file and it will change submit button text to “Hit me!” instead of default test “Post Comment”. Of course you can change this text to something more relevant to your website.

    // change submit button text in wordpress comment form
    function wcs_change_submit_button_text( $defaults ) {
        $defaults['label_submit'] = 'Hit me!';
        return $defaults;
    }
    add_filter( 'comment_form_defaults', 'wcs_change_submit_button_text' );
  • Disable Emojicons Feature Introduced in New WordPress 4.2

    How to Disable Emojicons Feature Introduced in New WordPress 4.2

    With the release of new WordPress 4.2 version, WordPress team introduced the use of Emojicons in your posts and comments. In order to make this new Emojicons feature to work, WordPress automatically adds JavaScript libraries in your page. Although it’s a nice feature to have for some bloggers who use Emojicons very frequently, but for some, it might be another useless bloat which they will probably never going to use on their website. If you are one of them then you might be wondering, how to disable Emojicons to gain your website speed back. So let’s see how to disable Emojicons in WordPress 4.2.

    In file /wp-includes/default-filters.php, WordPress adds all filters and actions that are used to add these Emojicons. All you need to do is find handle of each filters and actions and disallow WordPress to execute them using the functions remove_filter and remove_action. So here is the code snippet, you can paste in your functions.php file to disable Emojicons in your website.

    // disable Emojicons in WordPress 4.2
    function wpcs_remove_emojicons() {
    
        // Remove from comment feed and RSS
        remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
        remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
    
        // Remove from emails
        remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
    
        // Remove from head tag
        remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
    
        // Remove from print related styling
        remove_action( 'wp_print_styles', 'print_emoji_styles' );
    
        // Remove from admin area
        remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
        remove_action( 'admin_print_styles', 'print_emoji_styles' );
    
    }
    add_action( 'init', 'wpcs_remove_emojicons' );

    That’s it! Now you have disable Emojicons support on your website and removed all JavaScript libraries.

  • Get Category Slug of Current Category in WordPress

    How to Get Category Slug of Current Category in WordPress

    When developing a WordPress theme or a plugin, you may have come across times when you may wish to get category slug in certain pages. May be you are modifying the WordPress category archives or you may have some other reason for wanting to retrieve category slug, in this article we will show you a simple way to get category slug of current category and some other common category variables like name, ID and description.

    There are a variety of ways to return the variables of current category in WordPress, this method is my pick as it works anywhere and doesn’t need to be used in the loop. First we will get the category ID and then with the help of category ID, we will easily get category slug and other variables.

    You can use this code snippet in your theme files anywhere you wish. If your post have multiple categories associated with it, then this snippet will return category variables for first category only.

    <?php
        // get category slug in wordpress
        if ( is_single() ) {
            $cats =  get_the_category();
            $cat = $cats[0];
        } else {
            $cat = get_category( get_query_var( 'cat' ) );
        }
        $cat_slug = $cat->slug;
        echo $cat_slug;
    ?>

    Above WordPress snippet will print category slug only but you can also add couple of more category variables that you can use in your project.

    <?php
        // other category variables
        $cat_id = $cat->cat_ID;
        $cat_name = $cat->name;
        $cat_description = $cat->description;
    ?>
  • Hide Browser Upgrade Warning in WordPress

    How to Hide Browser Upgrade Warning in WordPress

    Many of you may have noticed the browser upgrade warning message on your WordPress admin panel dashboard. WordPress shows this warning message in admin panel if it detects you are using an old/outdated browser. Although it’s highly recommended to use latest browser on your system but sometime you don’t have the luxury of upgrading your browser immediately. Regardless of whatever reason you have for not upgrading your browser, there is a way to hide this annoying browser upgrade warning message from admin dashboard. Along with hiding browser upgrade warning message, you can also remove dashboard widgets from WordPress admin panel.

    To simply get rid of these notification / warning message, add following code snippet in your theme. Adding this snippet to the functions.php of your WordPress theme will completely disable the upgrade notification / warning being displayed.

    // hide browser upgrade warning in wordpress
    function wcs_disable_browser_upgrade_warning() {
        remove_meta_box( 'dashboard_browser_nag', 'dashboard', 'normal' );
    }
    add_action( 'wp_dashboard_setup', 'wcs_disable_browser_upgrade_warning' );
  • Keep Users Logged in For Longer in WordPress

    How to Keep Users Logged in For Longer in WordPress

    By default WordPress keep users logged in for maximum of 48 hours before logging them out or if they chose to close the browser before. If you click on “Remember Me” checkbox on the login page of your website, WordPress will keep you logged in for 14 days before logout and require you to re-authenticate again. What WordPress does, is create a login session cookie upon user login and set expiration date accordingly. After that time period, session cookie expires automatically and WordPress requires user to login again.

    It’s a security feature but if you manage number of WordPress websites then it becomes really very difficult to keep track of all of your highly complex username & password combinations. Searching for right credentials every two weeks can be a big hassle too. To help you with this issue, we can extend auto logout period in WordPress and keep users logged in for longer period than just 2 weeks.

    Paste this following code snippet in your functons.php file to increase the expiration time of the login session cookies, so that users can stay logged in longer.

    // keep users logged in for longer in wordpress
    function wcs_users_logged_in_longer( $expirein ) {
        // 1 month in seconds
        return 2628000;
    }
    add_filter( 'auth_cookie_expiration', 'wcs_users_logged_in_longer' );

    It’s important to note that the time in above functions is in seconds and we set users to stay logged in for a maximum period of 1 month.

  • Send Email Notification to User on Profile Updates

    How to Send Email Notification to User on Profile Updates

    On a project, I had a request from client who wants WordPress users to be notified by email when they update information in their user profile. I think its fair because most of the websites sends an automatic email notification when a user updates his profile and it’s good for security reasons too. But the small problem is that WordPress by default does not have such feature or an option in admin panel, but lucky WordPress provides a range of action hooks and filters that executes while WordPress perform any action. In this particular case, I used WordPress action profile_update to trigger email notifications. It’s also important to note that by default WordPress uses “From Email” as “[email protected]”, so you might want to change it to your contact email address too.

    To send email notification, we will be using WordPress mail function wp_mail and we will trigger it by action when a user profile information is updated, whether by user itself or by an admin. So following is the simple code snippet to send email notification to user. We can modify this snippet to inform website admin too but we will cover that in future articles. In this snippet I have added a sample profile update message which you should change if you want to provide more information about changed information or how to contact support if it was a mistake.

    By pasting this code snippet in your theme’s functions.php file, WordPress will automatically send email notification on any profile updates.

    // send email notification to user on profile updates
    function wcs_user_profile_update_notification( $user_id ) {
        $site_url = get_bloginfo( 'wpurl' );
        $site_title = get_bloginfo( 'name' );
        $user_info = get_userdata( $user_id );
        $to = $user_info->user_email;
        $to_name = $user_info->display_name;
        $subject = "User Profile Updated: " . $site_url;
    
        // message body
        $message = "Hello " . $to_name . ",\n\n";
        $message .= "Your profile has been updated!\n\n";
        $message .= $site_title . "\n";
        $message .= $site_url;
    
        wp_mail( $to, $subject, $message );
    }
    add_action( 'profile_update', 'wcs_user_profile_update_notification', 10, 2);
  • Automatically Delete Users After 7 Days In WordPress

    How to Automatically Delete Users After 7 Days In WordPress

    This is not the type of function you would require to use very often because it offers very specific feature to
    automatically delete users after predefined time. I was looking to implement this feature in a past project where my client was offering temporary access to a section on his website to many users, but he also wanted to revoke their access after a week. Deleting users manually from database worked for a while but later he
    often forgot to delete uses from database on timely basis which caused him lot of trouble and that’s when he asked to find a better solution to
    automatically delete users after 7 days.

    To do this I had to run a SQL query in WordPress to periodically check if there are users older than 7 days in WordPress users database table, and if there are, then delete those users at once. So I created this following function to delete used after 7 days of time.

    Simply paste this WordPress snippet in your theme’s functions.php file to automatically delete users after 7 days of time. Of course you can change this time limit and make it as small as 1 day or whatever time limit you prefer.

    // automatically delete users after 7 days in wordpress
    function wcs_auto_delete_users() {
        global $wpdb;
        $query = $wpdb->prepare( "SELECT ID FROM $wpdb->users WHERE datediff( now(), user_registered ) > 7" );
        if ( $oldUsers = $wpdb->get_results( $query, ARRAY_N ) ) {
            foreach ( $oldUsers as $user_id ) {
                wp_delete_user( $user_id[0] );
            }
        }
    }
    add_action( 'wcs_daily_clean_database', 'wcs_auto_delete_users' );
    
    wp_schedule_event( time(), 'daily', 'wcs_daily_clean_database' );
  • Add Async And Defer Attributes to JavaScript Elements

    How to Add Async And Defer Attributes to JavaScript Elements

    One of the suggestion that you always hear about JavaScript elements is to put them very close to the closing tag of the Web page. The main reason for that is that script elements are fetched and executed immediately when the browser encounter them. In most cases, this will improve website speed considerably.

    HTML5 introduces the async script attribute which helps to load scripts asynchronous. But older browsers and any version below Internet Explorer 10 does not support async attribute, therefore you can use defer attribute, that is very similar to the async attribute. Here is example usage of each in HTML.

    // async
    <script src="scripts.js" async></script>
    
    // defer
    <script src="scripts.js" defer></script>

    So question is which one do you use and what is the main difference between both. Well, this blog post explains the difference between async and defer attributes.

    Both async and defer scripts begin to download immediately without pausing the parser and both support an optional onload handler to address the common need to perform initialization which depends on the script. The difference between async and defer centers around when the script is executed. Each async script executes at the first opportunity after it is finished downloading and before the window’s load event. This means it’s possible (and likely) that async scripts are not executed in the order in which they occur in the page. The defer scripts, on the other hand, are guaranteed to be executed in the order they occur in the page. That execution starts after parsing is completely finished, but before the document’s DOMContentLoaded event.

    It’s very important to remember not to use the defer attribute on external script files that use the document.write or generate document content. But both, async and defer attributes can be used simultaneously on a script element.

    “The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that only support defer (and not async) to fall back to the defer behavior instead of the synchronous blocking behavior that is the default.”

    Here is a code snippet to add the async and defer attributes to all script elements. You can add this snippet to your functions.php file.

    // add async and defer to javascripts
    function wcs_defer_javascripts ( $url ) {
        if ( FALSE === strpos( $url, '.js' ) ) return $url;
        if ( strpos( $url, 'jquery.js' ) ) return $url;
        return "$url' async onload='myinit()";
    }
    add_filter( 'clean_url', 'wcs_defer_javascripts', 11, 1 );
  • Display Featured Post Thumbnails In WordPress Feeds

    How to Display Featured Post Thumbnails In WordPress Feeds

    WordPress does not allow featured post thumbnails in feeds even if you enable the post thumbnails support. But we have a solution for that. Here is how you can add post thumbnails to your WordPress RSS feeds with a simple function.

    Just copy and paste this code snippet in your theme functions.php file and your RSS feeds will display featured post thumbnails along with content.

    // display featured post thumbnails in WordPress feeds
    function wcs_post_thumbnails_in_feeds( $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', 'wcs_post_thumbnails_in_feeds' );
    add_filter( 'the_content_feed', 'wcs_post_thumbnails_in_feeds' );
  • Change Pages Link to Display Published Pages Only

    How to Change Pages Link to Display Published Pages Only

    In previous articles we have seen ways to remove submenu items and add link to all options in WordPress admin, In this article we will see how to change pages link in WordPress menu to display published pages.

    By default, Pages link in WordPress admin dashboard shows a list of all pages, no matter what their publishing status is. If you want to display published pages, you can filter your page list by visiting “Published” tab. It should not be a major problem for a regular blogger but if you have a lot of drafts then it would be difficult for you to identify publish pages on default pages list. Although you can always visit Published tab to display published pages but getting only to display them requires another click and full reload.

    WordPress provides a very nice way to change default dashboard menu links. With the help of WordPress action admin_menu, we can change the default behavior of menu links and force WordPress to display list of published pages only.

    To display published pages by default on pages link, simply paste this code snippet in your functions.php. You can then visit “All” tab to see full list of pages.

    PSD to WordPress Theme
    // change page link to display published pages only
    function wcs_change_admin_page_link() {
        global $submenu;
        $submenu['edit.php?post_type=page'][5][2] = 'edit.php?post_type=page&post_status=publish';
    }
    add_action( 'admin_menu', 'wcs_change_admin_page_link' );

    If you want to achieve the same for post link in admin dashboard then use following code snippet instead.

    // change post link to display published posts only
    function wcs_change_admin_post_link() {
        global $submenu;
        $submenu['edit.php'][5][2] = 'edit.php?post_status=publish';
    }
    add_action( 'admin_menu', 'wcs_change_admin_post_link' );