Fresh and Useful WordPress Hacks and Snippets

DZone 's Guide to

Fresh and Useful WordPress Hacks and Snippets

Tracking users, placing JavaScript in the right places, and adding disclaimers to old posts. Here are a set of really useful Wordpress snippets for you to try out

· Web Dev Zone ·
Free Resource

It’s been a long time that I haven’t published a list of fresh and super useful snippets and hacks to enhance your WordPress Theme or install. So, today I’m happy to show you this nifty list of coding tips to make your WordPress blog even more powerful.


Track Post Views Without Using a Plugin

A few plugins can help you tracking post views, but you actually don’t need a plugin to do that.

Here’s a set of functions that needs to be pasted in your theme’s functions.php file:

function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    return $count.' Views';
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        update_post_meta($postID, $count_key, $count);
// Remove issues with prefetching adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

Once done, you need to tell WordPress to track the views using the aforementioned functions. Paste the line below within the single.php file, inside the loop.


To display the view, use this function within the loop:

echo getPostViews(get_the_ID());

Source: WP Snipp

Capture Users’ Last Login Date

Some WordPress-based websites allow users to register. If your site allows user registration, you might want to know when was the last time a specific user logged in.

You first need to append the code below to your functions.php file:

// set the last login date
add_action('wp_login','wpsnipp_set_last_login', 0, 2);
function wpsnipp_set_last_login($login, $user) {
    $user = get_user_by('login',$login);
    $time = current_time( 'timestamp' );
    $last_login = get_user_meta( $user->ID, '_last_login', 'true' );
    update_usermeta( $user->ID, '_last_login', $time );
    update_usermeta( $user->ID, '_last_login_prev', $last_login );
    update_usermeta( $user->ID, '_last_login', $time );
// get last login date
function wpsnipp_get_last_login($user_id,$prev=null){
  $last_login = get_user_meta($user_id);
  $time = current_time( 'timestamp' );
  if(isset($last_login['_last_login_prev'][0]) && $prev){
          $last_login = get_user_meta($user_id, '_last_login_prev', 'true' );
  }else if(isset($last_login['_last_login'][0])){
          $last_login = get_user_meta($user_id, '_last_login', 'true' );
    update_usermeta( $user_id, '_last_login', $time );
    $last_login = $last_login['_last_login'][0];
  return $last_login;

Then, here’s how you display the latest login of a user:

// show last login date
global $current_user;
echo '<p>Previous: Login date: ' . date("Y-m-d h:m:s", wpsnipp_get_last_login($current_user->ID,true)) . '</p>';
echo '<p>Current: Login date: ' . date("Y-m-d h:m:s", wpsnipp_get_last_login($current_user->ID)) . '</p>';

Source: WP Snipp

Automatically Move JavaScript Files to the Footer

In order to improve the loading time of your WordPress blog, it is recommended that you move JavaScript files to the bottom of your HTML documents. Unfortunately, it isn’t always as easy as it seems, especially when using some plugins that inject code in the header. Here’s a simple solution to automatically move all JavaScript files to the bottom.

First, open your functions.php file and paste the following code in it:

 * Filter HTML code and leave allowed/disallowed tags only
 * @param string $text Input HTML code.
 * @param string $tags Filtered tags.
 * @param bool $invert Define whether should leave or remove tags.
 * @return string Filtered tags
function theme_strip_tags_content($text, $tags = '', $invert = false) {

    preg_match_all( '/<(.+?)[\s]*\/?[\s]*>/si', trim( $tags ), $tags );
    $tags = array_unique( $tags[1] );

    if ( is_array( $tags ) AND count( $tags ) > 0 ) {
        if ( false == $invert ) {
            return preg_replace( '@<(?!(?:'. implode( '|', $tags ) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text );
        else {
            return preg_replace( '@<('. implode( '|', $tags ) .')\b.*?>.*?</\1>@si', '', $text );
    elseif ( false == $invert ) {
        return preg_replace( '@<(\w+)\b.*?>.*?</\1>@si', '', $text );

    return $text;

 * Generate script tags from given source code
 * @param string $source HTML code.
 * @return string Filtered HTML code with script tags only
function theme_insert_js($source) {

    $out = '';

    $fragment = new DOMDocument();
    $fragment->loadHTML( $source );

    $xp = new DOMXPath( $fragment );
    $result = $xp->query( '//script' );

    $scripts = array();
    $scripts_src = array();
    foreach ( $result as $key => $el ) {
        $src = $result->item( $key )->attributes->getNamedItem( 'src' )->value;
        if ( ! empty( $src ) ) {
            $scripts_src[] = $src;
        } else {
            $type = $result->item( $key )->attributes->getNamedItem( 'type' )->value;
            if ( empty( $type ) ) {
                $type = 'text/javascript';

            $scripts[$type][] = $el->nodeValue;

    //used by inline code and rich snippets type like application/ld+json
    foreach ( $scripts as $key => $value ) {
        $out .= '<script type="'.$key.'">';

        foreach ( $value as $keyC => $valueC ) {
            $out .= "\n".$valueC;

        $out .= '</script>';

    //external script
    foreach ( $scripts_src as $value ) {
        $out .= '<script src="'.$value.'"></script>';

    return $out;

Once done, edit your header.php file. Replace the wp_head() tag by this:

$themeHead = ob_get_contents();
define( 'HEAD_CONTENT', $themeHead );

$allowedTags = '<style><link><meta><title>';
print theme_strip_tags_content( HEAD_CONTENT, $allowedTags );

And finally, place the code below into your footer.php file, just before the closing </body> tag.

<?php theme_insert_js( HEAD_CONTENT ); ?>

Source: WPRecipes

Display a Disclaimer on Older Posts

If you blog about technology, some articles that may have been useful 5 years ago can be totally outdated today. If a post is very old, it can be a good thing to warn your readers about it so they’ll know that the information they’re reading might be out of date.

Paste the following code in your single.php file, within the loop. Edited the text on line 7 as desired.

$ageunix = get_the_time('U');
$days_old_in_seconds = ((time() - $ageunix));
$days_old = (($days_old_in_seconds/86400));

if ($days_old > 365) {
  echo '<div class="disclaimer">DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.</div>'; 

Source: WPRecipes

Pre-Populate Editor With Default Content

If you often publish lists, reviews or any other kind of articles with a specific layout, this tip can be a great time saver, as it pre-populates your WordPress editor with the default content of your choice, and supports various post types.

Here’s the code to paste into your functions.php file. Save the file after modifying the values of the $content variables, and you’re done.

add_filter( 'default_content', 'pu_default_editor_content' );

function pu_default_editor_content( $content ) {
    global $post_type;

    switch( $post_type ) 
        case 'post':
            $content = 'Default content for blog posts.';

        case 'page':
            $content = 'Default content for pages.';

        case 'portfolio':
            $content = 'Default content for your portfolio pages.';

        case 'products':
            $content = 'Default content for blog posts.';

    return $content;

Source: Paulund

Hope these help!
javascript, snippets, wordpress

Published at DZone with permission of Jean-Baptiste Jung , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}