Turbo SEO Tools Website will be sold. If you are interested to purchase check details

10 Useful Code Snippets for WordPress Users


10 Useful Code Snippets for WordPress Users

10 Useful Code Snippets for WordPress Users

Remove Auto Linking of URLs in WordPress Comments

WordPress automatically turns URLs posted in comments into links. The downside to this feature is that it helps spammers publish links in their comments. You can remove this functionality with the following code snippet. Add the below snippets in functions.php file to Remove Auto Linking of URLs in WordPress Comments

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

Source

Require Minimum Comment Length

A good way to tackle spam and encourage better comments is to apply a minimum length for comments. This helps stop small irrelevant comments such as “Great post” and “Thanks!”. Add the below snippets in functions.php file for Require Minimum Comment Length

add_filter( 'preprocess_comment', 'minimal_comment_length' );
function minimal_comment_length( $commentdata ) {
    $minimalCommentLength = 20;
    if ( strlen( trim( $commentdata['comment_content'] ) ) < $minimalCommentLength ){
    wp_die( 'All comments must be at least ' . $minimalCommentLength . ' characters long.' );
    }
    return $commentdata;
}

Source

Remove the URL Field from WordPress Comment Form

Marking comments that have very long URLs in the website field will help you tackle spammers. However, if you find that spam is getting out of control, you may want to consider removing the website URL field altogether. If you implement the snippet below and configure your WordPress discussion settings so that any comment with a link is held for moderation; you can effectively stop all spam entirely. File to Edit: Functions.php

function remove_comment_fields($fields) {
    unset($fields['url']);
    return $fields;
}
add_filter('comment_form_default_fields','remove_comment_fields');

Source

Mark Comments with Very Long URLs as Spam

Spammers frequently link to web pages with very long URLs. Therefore, if someone publishes a comment and enters a long URL in the website field, there is a high chance that the comment was published by a spammer. The snippet below allows you to mark a comment as spam that has a website URL over 50 characters. You can increase or decrease this limit to suit your own needs.

<?php
  function rkv_url_spamcheck( $approved , $commentdata ) {
    return ( strlen( $commentdata['comment_author_url'] ) > 50 ) ? 'spam' : $approved;
  }
  add_filter( 'pre_comment_approved', 'rkv_url_spamcheck', 99, 2 );
?>

Source

Exclude Pages From Search

Doing searches in WordPress will pull results from both pages and posts, sometimes with not much relevance to your search query. To prevent this, you can filter the search results to show only those found in posts. Add this snippet to function.php to do this.

function SearchFilter($query) {
    if ($query->is_search) {
        $query->set('post_type', 'post');
    }
    return $query;
}
add_filter('pre_get_posts','SearchFilter');

Disable Links From User Comments

Links that are included in the comments form will instantly become a clickable link once they are posted and approved. This can be exploited by spammers, encouraging them to flood your comment section with a link to their "spammy" page. To counter this, you can add this filter to disable the click-ability of the link(s) and retain them simply as plain text.

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

Disable visual editor from posts and pages

Disable the 'visual' editor for both posts and pages and leave ‘text’.

add_filter('user_can_richedit' , create_function('' , 'return false;') , 50);

Add search form to WordPress nav menu

Add search form to wordpress nav menu by Adding this snippet to the functions.php of your wordpress theme will add the search form to your wordpress wp_nav_menu. Don’t forget to update the MENU-NAME to specify the menu you wish to display within, just in case you have multiple menus.

add_filter('wp_nav_menu_items', 'add_search_form', 10, 2);
function add_search_form($items, $args) {
if( $args->theme_location == 'MENU-NAME' )
        $items .= '<li class="search"><form role="search" method="get" id="searchform" action="'.home_url( '/' ).'"><input type="text" value="search" name="s" id="s" /><input type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" /></form></li>';
        return $items;
}

Display attachment thumbnail with image metadata

Adding this snippet within the loop of your index.php template file will display a list of all post attachments with the following metadata (Credit, Camera, Focal Length, Aperture, ISO, Shutter Speed, Time Stamp, Copyright).

<?php
if($images =& get_children( 'post_type=attachment' )){
   foreach($images as $id => $attachment ){
           echo '<div>';
           echo wp_get_attachment_image( $id, 'thumb' )."<br />";
           $meta = wp_get_attachment_metadata($id);
           echo "Credit:  ".$meta[image_meta][credit]."<br /> ";
           echo "Camera:  ".$meta[image_meta][camera]."<br />";
           echo "Focal length:  ".$meta[image_meta][focal_length]."<br />";
           echo "Aperture:  ".$meta[image_meta][aperture]."<br />";
           echo "ISO:  ".$meta[image_meta][iso]."<br />";
           echo "Shutter speed:  ".$meta[image_meta][shutter_speed]."<br />";
           echo "Time Stamp:  ".$meta[image_meta][created_timestamp]."<br />";
           echo "Copyright:  ".$meta[image_meta][copyright];
           echo '</div>';
   }
}
?>

Source

Add body_class to page templates in wordpress

Adding this snippet to the functions.php of your wordpress theme will let you add a body_class based on a specific page template.

  function add_archive_classes_to_page_templates($classes) {
                if (is_page_template('news.php')) {
                        $classes[] = 'news';
                }
                        return $classes;
        }
        add_filter('body_class', 'add_archive_classes_to_page_templates');

Source

Automatically Set Featured Image On A Post

It’s common practice to display a featured image that represents or describes a post. WordPress requires us to set this featured image manually. To make the process more efficient, we can set the featured image automatically by making the first image in the post the featured image. Use the following code snippet.

function autoset_featured() {
    global $post;
    $already_has_thumb = has_post_thumbnail($post->ID);
    if (!$already_has_thumb)  {
    $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
        if ($attached_image) {
            foreach ($attached_image as $attachment_id => $attachment) {
                set_post_thumbnail($post->ID, $attachment_id);
            }
        }
     }
}
add_action('the_post', 'autoset_featured');
add_action('save_post', 'autoset_featured');
add_action('draft_to_publish', 'autoset_featured');
add_action('new_to_publish', 'autoset_featured');
add_action('pending_to_publish', 'autoset_featured');
add_action('future_to_publish', 'autoset_featured');

Automatically Update Copyright Notice WordPress

By adding this to your footer.php template you can Automatically Update Copyright Notice WordPress in your footer every year automatically.

Copyright &copy; <?php echo the_date('Y'); ?> Website Name

Add An Edit Link To Your Posts & Pages

I find it very useful to have an edit link on posts and pages so that I can edit articles quickly if I see a mistake or want to adjust something. You can do this by simply adding the code below to your single.php and page.php templates. Make sure the function is added within the loop. Personally, I usually add it directly after the closing H1 tag that wraps around the_title().

<?php edit_post_link(__('Edit This')); ?>
Masum Billah

Authored By Masum Billah

My professional SEO and web development services are designed to deliver page one rankings in the major search engines. For your peace of mind, we only use safe, ethical and white hat SEO strategies! If you’re interested in working with me please drop me a line


leave a comment
Please post your comments here.