9 hacks and snippets to extend WordPress functionality

Shortcode to display external files

If you need to display external files without posts or pages, here’s a useful shortcode to help. The code below goes into your theme’s functions.php:

function show_file_func( $atts ) {
  extract( shortcode_atts( array(
    'file' => ''
  ), $atts ) );
 
  if ($file!='')
    return @file_get_contents($file);
}
 
add_shortcode( 'show_file', 'show_file_func' );

And here’s how you use it:

[show_file file="https://catswhocode.com/blog"]

Source: Specky Boy

Remove featured image when deleting a post

The code below will automatically delete the featured image associated with a post, when the post in question is deleted. Just insert it into functions.php.

add_action( 'before_delete_post', 'wps_remove_attachment_with_post', 10 );
function wps_remove_attachment_with_post($post_id) {
        if(has_post_thumbnail( $post_id ))
        {
          $attachment_id = get_post_thumbnail_id( $post_id );
          wp_delete_attachment($attachment_id, true);
        }
}

Source: WP Snipp

Set default fallback thumbnail for featured images

This handy code snippet allows you to define a default fallback image for posts where a featured image isn’t defined.

This code has to be pasted anywhere you want the featured image or its fallback to be displayed, most commonly on index.php and single.php. Edit line 4 and replace the URL with the URL of your fallback image.

<?php if ( has_post_thumbnail() ) {
the_post_thumbnail();
} else { ?>
<img src="<?php bloginfo('template_directory'); ?>/images/default-image.jpg" alt="<?php the_title(); ?>" />
<?php } ?>

Source: WP Expertz

Manually move scripts and CSS files to the footer

In order to optimize your website speed, you sometimes might want to move scripts and stylesheet on the footer of your site. This example features how to do it on a WordPress blog, but any developer with a little bit of experience can modify the code to make it fit any kind of website.

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:

<?php
ob_start();
wp_head();
$themeHead = ob_get_contents();
ob_end_clean();
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 ); ?>

Credit: Tomasz Dobrynski.

Only allow post author to reply to a comment on their post

If for some reason you only want to allow the post author to reply to comments, here’s a working solution. As often, you should add it to your theme’s functions.php file.

add_action( 'pre_comment_on_post', 'wpq_pre_commenting' );

function wpq_pre_commenting( $pid ) {
    $parent_id = filter_input( INPUT_POST, 'comment_parent', FILTER_SANITIZE_NUMBER_INT );
    $post = get_post( $pid );
    $cuid = get_current_user_id();

    if( ! is_null( $post ) && $post->post_author == $cuid && 0 == $parent_id ) {
        wp_die(	'Sorry, only post author can reply to a comment!' );
    }
} 

Source: GitHub

Display last modified date of a post

When you update your existing posts frequently, it is often more relevant to display the date of modification rather than the publishing date. Just paste this code where you want the date to be displayed. The function needs to be used within the loop.

<p>Last modified: <?php the_modified_date(); ?></p>

Source: WordPress Codex

Add Theme Editor shortcut to admin bar

If you often make modifications to your theme by using the built-in editor, it can be handy to add a shortcut to WordPress’ admin bar. Simply paste the code below in your functions.php file to proceed.

function admin_bar_theme_editor_option() {
    global $wp_admin_bar;
        if ( !is_super_admin() || !is_admin_bar_showing() )
        return;
        $wp_admin_bar->add_menu(
            array( 'id' => 'edit-theme',
            'title' => __('Edit Theme'),
                        'href' => admin_url( 'theme-editor.php')
        )
        );
    }
 
add_action( 'admin_bar_menu', 'admin_bar_theme_editor_option', 100 );

Source: WP Snippet

Schedule cron jobs with WordPress

Cron is a time-based job scheduler in Unix-like computer operating systems. It can be used within WordPress to schedule events, for example emptying your spam comment queue.
Here’s a basic code snippet to paste in your functions.php file, that will allow you to create a scheduled event.

<?php
add_action('my_hourly_event', 'do_this_hourly');

function my_activation() {
	if ( !wp_next_scheduled( 'my_hourly_event' ) ) {
		wp_schedule_event(time(), 'hourly', 'my_hourly_event');
	}
}
add_action('wp', 'my_activation');

function do_this_hourly() {
	// do something every hour
}
?>

Source: WP Snippets

Display a disclaimer on older posts

If you blog about technology, some articles that may have been useful 5 years ago can be completely 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. Edit the sentence 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 the latest WordPress version.</div>'; 
} 
?>

Source: CatsWhoCode

Leave a Reply

Your email address will not be published. Required fields are marked *