wordpress snippets

snippets to use for wordpress

function for no follow on all external links

function add_nofollow_content($content) {
$content = preg_replace_callback('/]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i', function($m) {
    if (strpos($m[1], "YOUR_DOMAIN_ADDRESS") === false)
        return '<a href="'.$m[1].'" rel="nofollow" target="_blank">'.$m[2].'</a>';
        return '<a href="'.$m[1].'" target="_blank">'.$m[2].'</a>';
    }, $content);
return $content;
add_filter('the_content', 'add_nofollow_content');

Fix Thumbnails on oceanwp


.post img {
max-width: 300px;
height: auto;
.single .thumbnail { text-align: center; }
.single .thumbnail img { width: 408px !important; }


Mobile Wordwrap around images oceanwp

@media only screen and (max-width: 959px) {
.alignleft, .alignright, .single-post.content-max-width .wp-block-image.alignleft, .single-post.content-max-width .wp-block-image.alignright {
display: block;



google analytics


add_action('wp_footer', 'ga'); 
function ga() { ?> 
// Paste your Google Analytics code here
<?php } ?>


excerpt 20

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

delete spam comment on the frontend

function delete_comment_link($id) { 
if (current_user_can('edit_post')) { 
echo '| <a href="'.admin_url("comment.php?action=cdc&amp;c=$id").'">del</a> ';
echo '| <a href="'.admin_url("comment.php?action=cdc&amp;dt=spam&amp;c=$id").'">spam</a>'; 

Add the following after edit_comment_link()


forbid spammers links

Spammers love to leave links in your comments. Stop those urls from turning into links.

remove_filter('comment_text', 'make_clickable', 9); 

Source: WP Recipes

dynamic footer date

Your footer should display your copyright something along the lines of 2005 – 2011. Usually people only have the current year, or they have some time in the past because they haven’t updated it. Use this snippet to make the date dynamic so you don’t have to worry about it every again.

function comicpress_copyright() { 
global $wpdb; 
$copyright_dates = $wpdb->get_results("
YEAR(min(post_date_gmt)) AS firstdate,
YEAR(max(post_date_gmt)) AS lastdate
post_status = 'publish' 
$output = ''; 
if($copyright_dates) { 
$copyright = "&copy; " . $copyright_dates[0]->firstdate; 
if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate) { 
$copyright .= '-' . $copyright_dates[0]->lastdate; 
$output = $copyright;
return $output;

Then insert this into your footer:

<?php echo comicpress_copyright(); ?>

Source: WP Beginner

add favicon

Everyone loves a favicon. They’re so cute! Use this in your functions.php to add one:

<span style="font-weight: normal;"> </span> 
// add a favicon to your
function blog_favicon() { 
echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.get_bloginfo('wpurl').'/favicon.ico" />'; 
add_action('wp_head', 'blog_favicon'); 

Source: WP Beginner

change social

WordPress, for some reason, still asks you to fill in your AIM and Yahoo IM. I don’t know about you but I haven’t logged into Yahoo IM for about 3 years, and AIM since before 2000. User this snippet to change it to the social media you actually use.

/* BEGIN Custom User Contact Info */ 
function extra_contact_info($contactmethods) { 
$contactmethods['facebook'] = 'Facebook'; 
$contactmethods['twitter'] = 'Twitter'; 
$contactmethods['linkedin'] = 'LinkedIn'; 
return $contactmethods; 
add_filter('user_contactmethods', 'extra_contact_info'); 
/* END Custom User Contact Info */ 

Then use this code wherever you want to display it:

<a href="<?php the_author_meta('facebook', $current_author->ID); ?>"></a> 

Source: Thomas Griffin

custom text on posts

You may want to add a custom piece of content under each post – perhaps a copyright notice, some advertising or you could just say “thanks for reading!”

function add_post_content($content) { 
if(!is_feed() &amp;&amp; !is_home()) { 
$content .= '<p>This article is copyright &copy; '.date('Y').'&nbsp;'.bloginfo('name').'</p>'; 
return $content;
add_filter('the_content', 'add_post_content'); 

Source: WP Recipes

Display Incremental Numbers Next to Each Published Post

This snippet lets you add numbers beside your posts. You could use Article 1, Article 2, Article 3; or Post 1, Post 2, Post 3; or whatever you want.

Add this to your functions:

function updateNumbers() { 
global $wpdb; 
$querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' "; 
$pageposts = $wpdb->get_results($querystr, OBJECT); 
$counts = 0 ; 
if ($pageposts): 
foreach ($pageposts as $post): 
add_post_meta($post->ID, 'incr_number', $counts, true); 
update_post_meta($post->ID, 'incr_number', $counts); 
add_action ( 'publish_post', 'updateNumbers' ); 
add_action ( 'deleted_post', 'updateNumbers' ); 
add_action ( 'edit_post', 'updateNumbers' ); 

Then add this within the loop:

<?php echo get_post_meta($post->ID,'incr_number',true); ?> 

Source: WP Recipes

list drafted posts

Want to tantalize your readers with what you’ve got to come? What to display an event that’s happening in the future? This snippet will let you list which posts you have in draft.

<div id="zukunft"> 
<div id="zukunft_header"><p>Future events</p></div> 
<?php query_posts('showposts=10&amp;post_status=future'); ?> 
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> 
<div > 
<p class><b><?php the_title(); ?></b><?php edit_post_link('e',' (',')'); ?><br /> 
<span><?php the_time('j. F Y'); ?></span></p> 
<?php endwhile; else: ?><p>No future events scheduled.</p><?php endif; ?> 

Source: WP Recipes

access denied to wp-admin

This code snippet is handy for preventing subscribers from having access to /wp-admin/. You can change the wp_user_level to whichever roles you want.

# Disable access to wp-admin for Subscribers
if ( is_user_logged_in() &amp;&amp; is_admin() ) { 
global $current_user; 
$user_info = get_userdata($current_user->ID); 
if ( $user_info->wp_user_level == 0 ) 
header( 'Location: '.get_bloginfo('home').'/wp-login.php?redirect='.get_bloginfo('home').'/wp-admin/' ); 

Source: Flowdrops

share via email copied from shun the plugin

Let everyone share your work. They can click on the button which opens the visitor’s default email client. Then they can email people and tell them how much they love you.

<?php echo "<a href="mailto:type%20email%20address%20here?subject=I%20wanted%20to
<?php bloginfo('name'); ?>&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;body=<?php the_title(); ?> - <?php the_permalink(); ?>"
title="Email to a friend/colleague"target="_blank">Share via Email</a>"; ?>

Source: Lava 360

facebook and twitter on every post

Add Facebook and Twitter to the bottom of each post

Easily add Facebook and Twitter to the bottom of your posts by adding this to your functions.php

function share_this($content){ 
if(!is_feed() &amp;&amp; !is_home()) { 
$content .= '<div class="share-this"> 
<a href="http://twitter.com/share" 
<script type="text/javascript" 
<div class="facebook-share-button"> 
scrolling="no" frameborder="0" style="border:none; 
overflow:hidden; width:200px; height:21px;" 
return $content;
add_action('the_content', 'share_this');

Source: WP Recipes

resize image instead of using original

Replace your uploaded image with the large image generated by WordPress. This will save space on your server, and save bandwidth if you link your thumbnail to the original image. I love things that speed up your website.

function replace_uploaded_image($image_data) { 
// if there is no large image : return
if (!isset($image_data['sizes']['large'])) return $image_data; 
// paths to the uploaded image and the large image
$upload_dir = wp_upload_dir(); 
$uploaded_image_location = $upload_dir['basedir'] . '/' .$image_data['file']; 
$large_image_location = $upload_dir['path'] . '/'.$image_data['sizes']['large']['file']; 
// delete the uploaded image
// rename the large image
// update image metadata and return them
$image_data['width'] = $image_data['sizes']['large']['width']; 
$image_data['height'] = $image_data['sizes']['large']['height']; 
return $image_data; 

Source: WP Recipes

enable multisite

No doubt all of our WPMU.org readers know this one already but to enable Mutlisite include this in your wp-config.php

define('WP_ALLOW_MULTISITE', true); 

Source: WP Theming

show tag cloud

Does what it says – show your tag cloud.

<?php wp_tag_cloud(array( 
'smallest' => 10,      // size of least used tag
'largest' => 18,       // size of most used tag
'unit' => 'px',        // unit for sizing
'orderby' => 'name',   // alphabetical
'order' => 'ASC',      // starting at A
'exclude' => 6         // ID of tag to exclude from list
)); ?> 

Source: Lava 360

paypal donate

Essential for non-profits and charities.

function donate_shortcode( $atts, $content = null) { 
global $post;extract(shortcode_atts(array( 
'account' => 'your-paypal-email-address',
'for' => $post->post_title,
'onHover' => '',
), $atts));</p> 
<p&gt;if(empty($content)) $content='Make A Donation'; 
return '<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;<span id="IL_AD3" class="IL_AD">business</span>='.$account.'&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;item_name=Donation for '.$for.'" title="'.$onHover.'">'.$content.'</a>'; 
add_shortcode('donate', 'donate_shortcode'); 

Source: Lava 360

paypal donate shortcode

If you are using the PayPal Donate function to accept donations from your website’s visitors, you can use this code snippet to create a shortcode, and thus make donating easier. First, paste the following in your functions.php file:

function donate_shortcode( $atts, $content = null) {
global $post;extract(shortcode_atts(array(
'account' => 'your-paypal-email-address',
'for' => $post->post_title,
'onHover' => '',
), $atts));
if(empty($content)) $content='Make A Donation';
return '<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business='.$account.'&item_name=Donation for '.$for.'" title="'.$onHover.'">'.$content.'</a>';
add_shortcode('donate', 'donate_shortcode');

Then, you can easily use the shortcode, such as:

My Text Here

using current year and showing modified

function year_shortcode() {
$year = date('Y');
return $year;
add_shortcode('year', 'year_shortcode');
Posted on &lt;?php the_time('F jS, Y') ?&gt;
          $u_time = get_the_time('U');
          $u_modified_time = get_the_modified_time('U');

      if ($u_modified_time != $u_time) {
                echo &quot;and last modified on &quot;;
                the_modified_time('F jS, Y');
                echo &quot;. &quot;;

remove images from p tags

// Stop images getting wrapped up in p tags when they get dumped out with the_content() for easier theme styling
function wpfme_remove_img_ptags($content){
return preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
add_filter('the_content', 'wpfme_remove_img_ptags');

require featured image

add_action('save_post', 'wpds_check_thumbnail');
add_action('admin_notices', 'wpds_thumbnail_error');
function wpds_check_thumbnail($post_id) {
    // change to any custom post type
    if(get_post_type($post_id) != 'post')
    if ( !has_post_thumbnail( $post_id ) ) {
        // set a transient to show the users an admin message
        set_transient( "has_post_thumbnail", "no" );
        // unhook this function so it doesn't loop infinitely
        remove_action('save_post', 'wpds_check_thumbnail');
        // update the post set it to draft
        wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
        add_action('save_post', 'wpds_check_thumbnail');
    } else {
        delete_transient( "has_post_thumbnail" );
function wpds_thumbnail_error()
    // check if the transient is set, and display the error message
    if ( get_transient( "has_post_thumbnail" ) == "no" ) {
        echo "<div id='message' class='error'><p><strong>You must select Featured Image. Your Post is saved but it can not be published.</strong></p></div>";
        delete_transient( "has_post_thumbnail" );

custom image size

if ( function_exists( 'add_image_size' ) ) {
    add_image_size( 'new-size', 300, 100, true ); //(cropped)
add_filter('image_size_names_choose', 'my_image_sizes');
function my_image_sizes($sizes) {
        $addsizes = array(
                "new-size" => __( "New Size")
        $newsizes = array_merge($sizes, $addsizes);
        return $newsizes;

login with email or username

function login_with_email_address($username) {
    $user = get_user_by('email',$username);
        $username = $user->user_login;
    return $username;

function change_username_wps_text($text){
    if(in_array($GLOBALS['pagenow'], array('wp-login.php'))){
        if ($text == 'Username'){$text = 'Username / Email';}

    return $text;
add_filter( 'gettext', 'change_username_wps_text' );

shortcode list for media

function add_sc_select(){
    global $shortcode_tags;
     /* ------------------------------------- */
     /* enter names of shortcode to exclude bellow */
     /* ------------------------------------- */
    $exclude = array("wp_caption", "embed");
    echo '&nbsp;<select id="sc_select"><option>Shortcode</option>';
    foreach ($shortcode_tags as $key => $val){
            $shortcodes_list .= '<option value="['.$key.'][/'.$key.']">'.$key.'</option>';
     echo $shortcodes_list;
     echo '</select>';
add_action('admin_head', 'button_js');
function button_js() {
        echo '<script type="text/javascript">
           jQuery("#sc_select").change(function() {
                          send_to_editor(jQuery("#sc_select :selected").val());
                          return false;

function to add a home link to your main menu

* Snippet Name: Function to add a HOME link to your primary navigation
* Snippet URL: http://www.wpcustoms.net/snippets/add-home-link-primary-navigation/
function addHomeMenuLink($menuItems, $args)
// change "primary_menu" to your theme's menu name
if('primary_menu' == $args->theme_location)
if ( is_front_page() )
$class = 'class="current-menu-item"';
$class = '';
$homeMenuItem = '<li '="" .="" $class="">' .
$args->before .
'<a href="' . home_url( '/' ) . '" title="Home">' .
$args->link_before .
'Home' .
$args->link_after .
'</a>' .
$args->after .
$menuItems = $homeMenuItem . $menuItems;
return $menuItems;
add_filter( 'wp_nav_menu_items', 'addHomeMenuLink', 10, 2 );

validate email


  • /**
  •  * Snippet Name: Check if email is valid
  •  * Snippet URL: http://www.wpcustoms.net/snippets/check-if-email-is-valid/
  •  */
  •  $email = 'testemail@gmail.com'// email address which we are verifying
  • if ( is_email( $email ) ) {
  •       echo 'valid email.';
  • }else {
  •       echo 'not a valid email';
  • }



Skip to toolbar