Quick Tip! 9 Handy WordPress Code Snippets (That You Really Should Know!) - Code Pixelz
  • Web Design
  • WordPress
  • Miscellaneous
    • HTML5
    • CSS
    • Mobile
    • Inspirations
    • Freelancer
  • WordPress 101
  • Get in touch
    • Advertise with us
    • Contribute
    • Contact Us
Skip to Content
Code Pixelz
  • Web Design
  • WordPress
  • Miscellaneous
    • HTML5
    • CSS
    • Mobile
    • Inspirations
    • Freelancer
  • WordPress 101
  • Get in touch
    • Advertise with us
    • Contribute
    • Contact Us
WordPress

Quick Tip! 9 Handy WordPress Code Snippets (That You Really Should Know!)

  • 2011-11-09
  • By Utsav Singh Rathour
  • 0 Comments

Here are some short but handy code snippets that may make your life as a WordPress developer a little easier. We’ll cover a little bit of everything, from how to automatically delete posts, how to quickly dish out a post thumbnail, to how to redirect users once they’ve logged in. Open up your text-replacement program and get ready to add a few new shortcuts!

Source: http://wp.tutsplus.com/tutorials/quick-tip-9-handy-wordpress-code-snippets-that-you-really-should-know/

We’ll start off with a few simple one-liners.

[list_adsense]


1. Hide The Front-End Dashboard Bar

Since v3.1, WordPress has provided a front-end admin bar for all users. Depending on your intent, this can detract from the look of your site. To disable it, use the show_admin_bar function:

show_admin_bar(FALSE);

You can also disable this from your User Profile, but this is especially useful if you’ve got a ton of authors/members on the site and you need to disable the bar altogether.


2. Empty Trashed Posts Automatically

Trashed posts can build up if you forget to delete them permanently. Use this code in /wp-config.php to empty your trashed posts:

  1. define(‘EMPTY_TRASH_DAYS’, 5 );

3. Turn On WordPress Internal Debugger

When you’re developing, you need to see the errors your code is throwing up. Keep in mind that not all errors stop a script from executing but they are errors nevertheless, and they may have strange effects upon your other code. So, turn on WordPress debug by placing this in your /wp-config.php:

  1. define(‘WP_DEBUG’, TRUE);

You may be amazed by what you see in the footer. Remember to turn debugging off when your site is ready to go public. Debug info can be valuable to hackers.


4. Redirect Users After They Login

When a user logs in, they normally get sent straight to their dashboard. This may not be the experience you want your users to have. The following code uses the login_redirect filter to redirect non-administrators to the home page:

  • add_filter(“login_redirect”, “subscriber_login_redirect”, 10, 3);
  • function subscriber_login_redirect($redirect_to, $request, $user){
  • if(is_array($user->roles)){
  • if(in_array(‘administrator’, $user->roles)) return home_url(‘/wp-admin/’);
  • }
  • return home_url();
  • }

Based on the user’s role, you could send them to any page you like.


5. Show A Default Post Thumbnail Image

Since v2.9, WordPress has provided a post thumbnail image option, just like the images you see here on wp.tutsplus. On the admin post page it’s called ‘Featured Image’. But if you don’t have an image for your post, you can simply call a default image.

Within the loop:

  1. if(has_post_thumbnail()){
  2. the_post_thumbnail();
  3. }else{
  4. echo ‘<img src=”‘ . get_bloginfo(‘template_directory’) . ‘/images/default_post_thumb.jpg” />’;
  5. }
  • check if the post has a thumbnail with has_post_thumbnail
  • if so, display it with the_post_thumbnail()
  • otherwise, generate an img tag for you default thumbnail image

You could even have a bunch of default images and pick one at random


6. Show “Time Ago” Post Time For Posts And Comments

Instead of: Posted on October, 12, 2011, we can have: Posted 2 days ago.

As used in the loop:

  1. echo human_time_diff(get_the_time(‘U’), current_time(‘timestamp’)) . ‘ ago’;
  • human_time_diff() converts a timestamp value to a friendly form
  • get_the_time() gets the time the post was made, with ‘U’ parameter gets value as a Unix timestamp
  • current_time() gets the current time, with ‘timestamp’ parameter gets value as a Unix timestamp

Use it on comments as well:

  1. echo human_time_diff(get_comment_time(‘U’), current_time(‘timestamp’)) . ‘ ago’;

Or maybe show the regular date/time of the post only if more than a week ago, else show the time ago:

  1. $time_diff = current_time(‘timestamp’) – get_the_time(‘U’);
  2. if($time_diff < 604800){//seconds in a week = 604800
  3. echo ‘Posted ‘ . human_time_diff(get_the_time(‘U’), current_time(‘timestamp’)) . ‘ ago’;
  4. }else{
  5. echo ‘Posted on ‘ . get_the_date() . ‘, ‘ . get_the_time();
  6. };

7. Style Post Author Comments Differently

It’s nice for users to be able to see when the author of a post makes a comment on the post, just like we do here on wp.tutsplus. All we have to do is add a class to the comment wrapper and then style it in the theme.

In order to find which comments are made by the post author, we use this code to output a class name:

  1. if($comment->user_id == get_the_author_meta(‘ID’)){
  2. echo ‘<div class=”comment_wrapper author_comment”>’;
  3. }else{
  4. echo ‘<div class=”comment_wrapper”>’;
  5. }

We compare the user ID of the comment with the post author ID from get_the_author_meta. If they match, we echo a class of author_comment which we can then style with css.


8. Show User, Post And Comment Info For Your WordPress Site

You can query your WordPress database directly to show handy site info. Put this function in your functions.php and call it anywhere in your template files with get_site_data()

  1. function get_site_data(){
  2. global $wpdb;
  3. $users = $wpdb->get_var(“SELECT COUNT(ID) FROM $wpdb->users”);
  4. $posts = $wpdb->get_var(“SELECT COUNT(ID) FROM $wpdb->posts WHERE post_status = ‘publish'”);
  5. $comments = $wpdb->get_var(“SELECT COUNT(comment_ID) FROM $wpdb->comments”);
  6. echo ‘<p>’ . $users . ‘ members have made ‘ . $comments . ‘ comments in ‘ . $posts . ‘ posts</p>’;
  7. }

This is better than calling some of the native WordPress functions as it counts all post types and only currently published posts.


9. Add A JavaScript File Correctly

WordPress gives us the wp_enqueue_script function so we can add scripts safely.

Say we have a scripts dir under our template dir, and in there we have a script called do_stuff.js. So we have url_to_template_dir/scripts/do_stuff.js

Let’s include our script the right way. This must be included before the wp_head call in your header file:

  1. $script_url = get_template_directory_uri() . ‘/scripts/do_stuff.js’;
  2. wp_enqueue_script(‘do_stuff’, $script_url);

Here we concatenate our script path and name onto the output of the WordPressget_template_directory_uri function. We then enqueue the script by providing a handle (for possible later reference) and the url to our script. WordPress will now include our script in each page.

The real advantage to all of this is that, say our do_stuff script was a jQuery script, then we would also need to have jQuery loaded.

Now, jQuery is included by default in WordPress, and has been pre-registered with the handle jquery. So all we need do is enqueue our jQuery, then enqueue our do_stuff.js, like this:

  1. wp_enqueue_script(‘jquery’);
  2. $script_url = get_template_directory_uri() . ‘/scripts/do_stuff.js’;
  3. wp_enqueue_script(‘do_stuff’, $script_url, array(‘jquery’));

Note the third parameter to wp_enqueue_script for do_stuff: that tells WordPress that our do_stuff script is dependent on the file with the handle jquery. This is important because it means that jquery will be loaded before do_stuff. In fact, you could have the enqueue statements in reverse order and it wouldn’t matter since defining a script’s dependencies allows WordPress to put the scripts in correct loading order so that they all work happily together.

Show Love

  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Twitter (Opens in new window)

Related

Empty Trashed Posts Automatically Hide The Front-End Dashboard Bar Redirect Users After They Login Show “Time Ago” Post Time For Posts And Comments Show A Default Post Thumbnail Image Style Post Author Comments Differently using wordpress Turn On WordPress Internal Debugger

Article By Utsav Singh Rathour

Utsav Singh Rathour is a WordPress Enthusiast and a blogger with over 10 years of experience and believes in building applications that not only tackles the problem but gives users a better interface. He is founder of Code Pixelz Media and blogs mainly at this place. Follow him at @rathour

Author Archives Author Website

Post navigation

Next Post Infographics, Pictures that...
Previous Post New Year and a new beginning

Related Posts

How-to-recover-lost-password-in-WordPress-CodePixelz
tutorial

How to Recover a Lost Password in WordPress?

  • 2020-04-24
  • 0 Comments
Mistakes Beginner WordPress Users Make-Code Pixelz
WordPress

8 Common Mistakes Beginner WordPress Users Make

  • 2019-11-15
  • 0 Comments
WordPress-Uses-to-builda-website-CodePixelz
WordPress

Top 5 Important Reasons to Use WordPress for a Website

  • 2019-10-21
  • 0 Comments
improve WordPress website speed-Code Pixelz
Miscellaneous

5 Most Effective Ways to Improve WordPress Website Speed

  • 2019-08-19
  • 0 Comments
WordPress theme building-Codepixelz
tutorial

Getting started with the basic of WordPress Theme Building

  • 2019-08-02
  • 0 Comments

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

 

Need Job Listing Theme?

Robolist-Job-Listing-Theme-Code-Themes

 

Need Hosting?

Web Hosting

  • Latest Posts
  • Most Popular

The most essential WordPress Directory...

  • 2022-03-21
0

Things to consider when hiring a remote...

  • 2021-12-20
0

Must-Have WordPress Plugins for...

  • 2021-12-08
0

30+ Top Best Premium & Free...

  • 2021-11-24
0

Holiday WordPress Deals for 2021

  • 2021-11-17
0
WordPress Ajax Form-CodePixelz

Tutorial : How to create a Ajax Form in...

  • 2019-08-05
6
Foundations, Free WordPress themes for Architects

Top 25+ Free WordPress themes for...

  • 2021-09-13
0
Opal-Hotel-Room-Booking-WordPress-plugin-CodePixelz

Top 7+ Free Hotel Booking WordPress...

  • 2020-06-22
0
awesome-CSS-buttons

Awesome CSS Buttons

  • 2017-01-13
2

Need help with WordPress?



Popular Posts

  • Tutorial : How to create a Ajax Form in WordPress
  • Top 25+ Free WordPress themes for Architects & Construction Companies (Updated)
  • Top 7+ Free Hotel Booking WordPress Plugins for Accomodations (Updated)
  • Awesome CSS Buttons
  • 20+ Best Free Lawyer WordPress Themes for Law Firms and Attorneys (Updated)

Follow us on Twitter

My Tweets

Pages

  • About Code Pixelz
  • Advertise with us
  • Contribute
  • Get in touch
  • Privacy Policy
Powered by Magazine theme from Code Themes Co
Back To Top
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT