Shun the Plugin: 100 WordPress Code Snippets from Across the Net
blog

BlogOur collection of thoughts, advice, experiments and other activities going on in and out of the studio.

Shun the Plugin: 100 WordPress Code Snippets from Across the Net

Monday,February 12, 2018 / / KrishaWeb

100 WordPress Code Snippets from Across the Net

Compared to the plug-ins, WordPress code snippets seem like a better option because they do not crowd the page as plug-ins do. Extremely handy both developers and users prefer this to customize themes. When you want to know about some aspect of WordPress searching for snippets is a good idea because someone has already been there and done that.

Find the perfect snippet to achieve your purpose without the need to sift through the plug-ins, testing each to determine its compatibility to your site. Even if you do not know anything about coding it is okay because successfully use code snippets, you just need to know which one to use and its proper placement.

How to Use Code Snippets

There are different ways of using code snippets and the usual way is by using functions.php file but remember that this is a theme specific file. This means that in case you wish to change the WordPress theme afterwards with the file containing functions that are non-theme specific, you need to begin from scratch. Also, for making changes to the parent theme followed by update, changes made in functions.php file become overwritten so that it becomes necessary to remake these. Some ways to resolve the issue are the following:

  • Create custom plug-ins but you need to have knowledge of this.
  • Use the code snippets, the snippet plug-in to facilitate addition of code snippets on site without their manual addition to functions.php.
  • Use theme specific plug-in as this offers the least amount of resistant. Hunt for the compatible plug-ins.

Backing up WordPress site prior to making any changes is crucial. Other than that, it is also necessary to save the original functions.php file so that you will be able to restore originals when things go wrong.

Words of Warning

 

Backup of the site is critical: Things might go wrong it can be something simple as too many number of spaces or issues related to plug-in compatibility. Even when you are sure that everything would be right, taking precautions is a good thing.

Use of code snippets for theme: When two functions have the same name for theme, it does not work and hours go by as you search for the problem. When creating and releasing snippets for use in plug-ins or themes rename functions individually to prevent any problems later. Many functions tend to have quite distinctive names.

Basics

 

Highlight search terms: Highlight search terms or keywords to boost search functionality in results from search engines. Open search.php, find the_title() function, replace with echo $title.

Shorten blog excerpts: Shorten the too long blog posts to only 20 words to clean up the post page appearance.

Function new_excerpt_length($trength) {return 20;}

add_filter(‘excerpt_length’,’new_excerpt_length’);

Automatically link to Twitter usernames: Snippet keeps eye on the posts and when you use the Twitter username for example, it creates link automatically for you.

Switch on Maintenance Mode: You have a snippet for getting to the quick maintenance mode. All you need to do is to comment this out for switching this on.

function maintenace_mode() { 

if ( !current_user_can( 'edit_themes' ) || !is_user_logged_in() ) { 
die('Maintenance.'); 
} 
} 
add_action('get_header', 'maintenace_mode'); 

Add a Shortcode to Widgets: Despite of wishing to add shortcode to widget, you may not be able to do this easily. This has changed today however because your can add shortcode to text widget with appropriate WP code snippet.

add_filter('widget_text', 'do_shortcode') 

Add Favicon: These tend to be highly cute and this is where their charm lies. Use appropriate snippet in functions.php for adding 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');

Remove Menus in WordPress Dashboard: Sometimes, clients might have confusion regarding the presence of menu section in posts. This might create posts and not pages and so the client might call you to complain regarding the non-showing of pages. It happens to everyone and the best thing to do would be to remove Menus from WordPress dashboard with appropriate code snippet.

 

function remove_menus () { 

global $menu;
$restricted = array(__('Dashboard'), __('Posts'), __('Media'), __('Links'), __('Pages'), __('Appearance'), __('Tools'), __('Users'), __('Settings'), __('Comments'), __('Plugins')); 
end ($menu); 

while (prev($menu)){ 
$value = explode(' ',$menu[key($menu)][0]); 

if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);} 
} 
} 
add_action('admin_menu', 'remove_menus');

 Add Custom Dashboard Widgets: You can use code snippet to add extra dashboard widgets to give the clients required info.

add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets'); 
function my_custom_dashboard_widgets() { 

global $wp_meta_boxes; 
wp_add_dashboard_widget('custom_help_widget', 'Theme Support', 'custom_dashboard_help'); 
} 
function custom_dashboard_help() { 
echo '<p>Welcome to Custom Blog Theme! Need help? Contact the developer <a href="mailto:yourusername@gmail.com">here</a>. For WordPress Tutorials visit: <a href="http://www.wpbeginner.com"target="_blank">WPBeginner</a></p>'; 
}

Automatically Add a Search Box to Your Nav Menu: Use the right code snippet.

add_filter('wp_nav_menu_items','add_search_box', 10, 2); 
function add_search_box($items, $args) { 
ob_start(); 
get_search_form(); 
$searchform = ob_get_contents(); 
ob_end_clean(); 
$items .= '<li>' . $searchform . '</li>'; 

return $items; 
}

Breadcrumbs without a plugin: Now it is possible to create the required breadcrumb trails minus the use of plug-ins and all you need to do is to insert code snippet into functions.php.

functions.php

function the_breadcrumb() { 
echo '<ul id="crumbs">'; 

if (!is_home()) { 
echo '<li><a href="'; 
echo get_option('home'); 
echo '">'; 
echo 'Home'; 
echo "</a></li>"; 

if (is_category() || is_single()) { 
echo '<li>'; 
the_category(' </li><li> '); 

if (is_single()) { 
echo "</li><li>"; 
the_title(); 
echo '</li>'; 
} 
} elseif (is_page()) { 
echo '<li>'; 
echo the_title(); 
echo '</li>'; 
} 
} 

elseif (is_tag()) {single_tag_title();} 

elseif (is_day()) {echo"<li>Archive for "; the_time('F jS, Y');echo'</li>';} 

elseif (is_month()) {echo"<li>Archive for "; the_time('F, Y');echo'</li>';} 

elseif (is_year()) {echo"<li>Archive for "; the_time('Y');echo'</li>';} 

elseif (is_author()) {echo"<li>Author Archive"; echo'</li>';} 

elseif (isset($_GET['paged']) &amp;&amp; !empty($_GET['paged'])) {echo "<li>Blog Archives"; echo'</li>';} 

elseif (is_search()) {echo"<li>Search Results"; echo'</li>';} 
echo '</ul>'; 
}

Insert into header.php

<?php the_breadcrumb(); ?>

Pagination: You might like to add pagination in the bottom portion of blog. This is easy to do by inserting appropriate code snippet into the functions.php file.

functions.php

function my_paginate_links() { 

global $wp_rewrite, $wp_query; 
$wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1; 
$pagination = array( 
'base' => @add_query_arg('paged','%#%'),
'format' => '',
'total' => $wp_query->max_num_pages,
'current' => $current,
'prev_text' => __('« Previous'),
'next_text' => __('Next »'),
'end_size' => 1,
'mid_size' => 2,
'show_all' => true, 
'type' => 'list' 
); 

if ( $wp_rewrite->using_permalinks() ) 
$pagination['base'] = user_trailingslashit( trailingslashit(remove_query_arg( 's', get_pagenum_link( 1 ) ) ) . 'page/%#%/', 'paged'); 

if ( !empty( $wp_query->query_vars['s'] ) ) 
$pagination['add_args'] = array( 's' => get_query_var( 's' ) ); 
echo paginate_links( $pagination ); 
} 

Use CSS to style it how you want.

Google Analytics Without Editing Theme: You might have updated the parent theme only to realize sometime later that you forgot to add the tracking code for Google Analytics. Now, what is going to happen because you are going to lose the vital statistics? Do not worry because it is possible to solve this problem simply with the addition of the tracking code into the functions.

<?php 

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

Add Custom User Contact Info: You may not know the reason but WP asks for Yahoo IM and your AIM even now. Most people do not even remember when they last logged into AIM or Yahoo IM. You do not have to remember because now you can use the code snippet for changing this to your active social media account, one that you use now.

/* BEGIN Custom User Contact Info */ 
function extra_contact_info($contactmethods) { 
unset($contactmethods['aim']); 
unset($contactmethods['yim']); 
unset($contactmethods['jabber']); 
$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>

Display Most Popular Post from a Specific Category: From the featured category of the posts, you might like to display the most popular posts only or from the books category. You have a snippet for achieving the results you want.

<?php 
$args=array( 
'cat' => 3,
'orderby' => 'comment_count',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 6,
'caller_get_posts'=> 1 
); 
$my_query = null;
$my_query = new WP_Query($args); 

if( $my_query->have_posts() ) { ?> 
<ul> 
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?> 
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?> 
</ul> 
<?php } 

wp_reset_query(); ?> 

Remember to change this line to the category you want:

‘cat’ => 3,
And set this line to how many posts you want to display:

‘posts_per_page’ => 6,

 

Popular Posts Based on Comment Count: Will not it be interesting if you could list the popular posts based upon related number of the comments? You can do this with a code snippet.

<h2>Popular Posts</h2> 
<ul> 
<?php $result = $wpdb->get_results("SELECT comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 10");
foreach ($result as $post) {
setup_postdata($post);
$postid = $post->ID;
$title = $post->post_title;
$commentcount = $post->comment_count;
if ($commentcount != 0) { ?>
<li><a href="<?php echo get_permalink($postid); ?>" title="<?php echo $title ?>">
<?php echo $title ?></a> {<?php echo $commentcount ?>}</li> 
<?php } } ?> 
</ul> 

Different RSS Feed for Each Custom Post Type/Taxonomy: At a glance, this might seem like an incredible difficult to achieve but this is not because you just need to append customized post type into the URL followed by addition of custom taxonomy with this.

http://www.yoursite.com/feed/?post_type=book

Then you can add a custom taxonomy to it too.

http://www.yoursite.com/feed/?post_type=book&amp;genre=romance

Display Recent Comments with Gravatar: This is for the times when you are looking for a simple way for achieving your desired results without using the customary plug-ins. Show off the latest comments into sidebar with gravatar. Paste this to the sidebar.php.

<?php $comments = get_comments('status=approve&amp;number=5'); ?> 
<ul> 
<?php foreach ($comments as $comment) { ?> 
<li> 
<?php echo get_avatar( $comment, '35' ); ?> 
<a href="<?php echo get_permalink($comment->ID); ?>#comment-<?php echo$comment->comment_ID; ?>" title="on <?php echo $comment->post_title; ?>"> <?php echo strip_tags($comment->comment_author); ?>: <?php echowp_html_excerpt( $comment->comment_content, 35 ); ?>... </a> 
</li> 
<?php } ?> 
</ul> 

Remove Autolinks in Comments: Spammers have the habit of leaving links in the comments section but now it is possible for you to stop the URLs posted by the spammers from transforming into links with code snippets.

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

Display Number of Comments: Use the appropriate code snippet to achieve this result easily.

<?php 
$commcount = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1'"); 

if (0 < $commcount) $commcount = number_format($commcount); 
echo "Our users have made ".$commcount." comments, care to join in?"; 
?> 

Insert Author Box: To do this all you need to do is to insert code snippet into single.php after articles tag.

<div> 
<div> 
<div><?php echo get_avatar( get_the_author_email(), '80' ); ?></div> 
</div> 
<div> 
<div><?php the_author_meta( "display_name" ); ?></div> 
<div><?php the_author_meta( "user_description" ); ?></div> 
<div><?php if (get_the_author_url()) { ?><a href="<?phpthe_author_url(); ?>">Visit <?php the_author(); ?>'s website</a><?php }else { } ?></div> 
</div> 
<div></div> 
</div> 

And here’s some CSS to make it pretty.

 

.author-box { padding: 10px; background: #ccc; border: 1px solid #333;}
.author-left {float:left; width: 80px; margin: 0 15px 0 0;} 
.author-right {float:left; font-size: 13px; margin: 5px 0 0 10px;} 
.author-pic {border: 1px solid: #ccc;} 
.author-name {font-weight:bold;} 
.author-bio {padding: 5px 0 5px 0;} 
.author-url {color: #555;} 
.author-url a {color: #000;} 
.author-url a:hover {color: #333;}
.clear {clear:both}

Force Users to Log in Before Reading a Post: You can use this for restricted posts such as those for subscribers only.

 

function my_force_login() { 

global $post;

if (!is_single()) return; 
$ids = array(188, 185, 171); // array of post IDs that force login to read


if (in_array((int)$post->ID, $ids) &amp;&amp; !is_user_logged_in()) { 
auth_redirect(); 
} 
} 

And then put this at the top of your header:

<?php my_force_login(); ?>

Protect your wp-config.php: protect something precious by adding this snippet to .htaccess file.

<Files wp-config.php> 
order allow,deny
deny from all
</Files> 

Add Facebook and Twitter to the bottom of each post: add the snippet to functions.php for achieving desired result.

 

function share_this($content){ 

if(!is_feed() &amp;&amp; !is_home()) { 
$content .= '<div class="share-this"> 
<a href="http://twitter.com/share" 

class="twitter-share-button" 
data-count="horizontal">Tweet</a> 
<script type="text/javascript" 
src="http://platform.twitter.com/widgets.js"></script> 

<div class="facebook-share-button"> 
<iframe
src="http://www.facebook.com/plugins/like.php?href='.

urlencode(get_permalink($post->ID)) 
.'&amp;layout=button_count&amp;show_faces=false&amp;width=200&amp;action=like&amp;colorscheme=light&amp;height=21" 
scrolling="no" frameborder="0" style="border:none; 
overflow:hidden; width:200px; height:21px;" 
allowTransparency="true"></iframe> 
</div> 
</div>'; 
} 

return $content;
} 
add_action('the_content', 'share_this');

Display your number of Twitter Followers: do this but do not forget to insert own username.

<?php 
$twit =file_get_contents('http://twitter.com/users/show/USERNAME.xml'); 

$begin = '<followers_count>'; $end = '</followers_count>'; 
$page = $twit;
$parts = explode($begin,$page); 
$page = $parts[1]; 
$parts = explode($end,$page); 
$tcount = $parts[0]; 

if($tcount == '') { $tcount = '0'; } 
echo '<b> '.$tcount.' </b> Followers'; 
?>

Display Your Facebook Fans: show of your fans, use ‘your page ID’ instead of YOUR-PAGE-ID.

 

<?php 
$page_id = "YOUR PAGE-ID"; 
$xml = @simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;query=SELECT%20fan_count%20FROM%20page%20WHERE%


20page_id=".$page_id."") or die ("a lot"); 
$fans = $xml->page->fan_count;
echo $fans; 
?>

Tiny URL: get this with appropriate snippet.

function get_tiny_url( $url ) 
{ 
$tiny_url = file_get_contents( "http://tinyurl.com/api-create.php?url=".$url ); 


return $tiny_url;
}

B/1, Nikumbh Complex,
Opp. Tomato’s Restaurant,
C.G. Road, Navrangpura,
Ahmedabad, Gujarat 380009.

full-service