- Last updated on: June 15, 2020
22 Handy WordPress Code Snippets
It helps when coding your own themes to have an array of code snippets to hand that you can incorporate into your the theme, I have collected a huge number of hacks and code snippets over the years which I will be sharing with you in this post, I hope you find them helpfull.
Conditional Tags
Conditional tags are very usefull as you can use them for things like a highlighted item in a nav menu, show a different css class depending which page you are on.
[sourcecode language=”php”]
<ul id="nav">
<li<?php if ( is_home() || is_category() || is_archive() || is_search() || is_single() || is_date() ) { echo ‘ class="current"’; } ?>><a href="#">Gallery</a></li>
<li<?php if ( is_page(‘about’) ) { echo ‘ class="current"’; } ?>><a href="#">About</a></li>
<li<?php if ( is_page(‘submit’) ) { echo ‘ class="current"’; } ?>><a href="#">Submit</a></li>
</ul>
[/sourcecode]
Source: Web Designer Wall
Post Author Info Box
If you have a multi-author blog its nice to show some author info after the blog post. These tags will display various info about the post author, add them to your single.php file :
Author’s Gravatar
[sourcecode language=”php”]
<?php echo get_avatar( get_the_author_email(), $size = ‘100’ ); ?>
[/sourcecode]
Author’s Website Link
[sourcecode language=”php”]
<a href="<?php the_author_url(); ?>">Author’s Website</a>
[/sourcecode]
Author’s About Me Info
[sourcecode language=”php”]
<?php the_author_description(); ?>
[/sourcecode]
Source: Tutorial Mag
Highlight Author’s Comments
This will allow you to apply different styling in the comments section to your own comments so they stand out from normal users:
Add this to your stylesheet :
[sourcecode language=”php”]
.authcomment {
background-color: #B3FFCC !important;
}
[/sourcecode]
Edit comments.php like so :
[sourcecode language=”php”]
<li class=”<?php
/* Only use the authcomment class from style.css if the user_id is 1 (admin) */
if (1 == $comment->user_id)
$oddcomment = “authcomment”;
echo $oddcomment;
?>”
[/sourcecode]
Source: Matt Cutts
Disable HTML in Comments
If you dont want people to be able to use the default HTML tags that are allowed in WordPress, add this code to your theme’s functions.php file:
[sourcecode language=”php”]
// This will occur when the comment is posted
function plc_comment_post( $incoming_comment ) {
// convert everything in a comment to display literally
$incoming_comment[‘comment_content’] = htmlspecialchars($incoming_comment[‘comment_content’]);
// the one exception is single quotes, which cannot be #039; because WordPress marks it as spam
$incoming_comment[‘comment_content’] = str_replace( "’", ‘'’, $incoming_comment[‘comment_content’] );
return( $incoming_comment );
}
// This will occur before a comment is displayed
function plc_comment_display( $comment_to_display ) {
// Put the single quotes back in
$comment_to_display = str_replace( ‘'’, "’", $comment_to_display );
return $comment_to_display;
}
add_filter( ‘preprocess_comment’, ‘plc_comment_post’, ”, 1);
add_filter( ‘comment_text’, ‘plc_comment_display’, ”, 1);
add_filter( ‘comment_text_rss’, ‘plc_comment_display’, ”, 1);
add_filter( ‘comment_excerpt’, ‘plc_comment_display’, ”, 1);
[/sourcecode]
Source: Web Developer Plus
Display AdSense Ads to Search Engines Visitors Only
Search engine visitors are more likely to click on your adsense ads, so to preserve your CTR this is a great tip to use :
Place this code in your functions.php file:
[sourcecode language=”php”]
function scratch99_fromasearchengine(){
$ref = $_SERVER[‘HTTP_REFERER’];
$SE = array(‘/search?’, ‘images.google.’, ‘web.info.com’, ‘search.’, ‘del.icio.us/search’, ‘soso.com’, ‘/search/’, ‘.yahoo.’);
foreach ($SE as $source) {
if (strpos($ref,$source)!==false) return true;
}
return false;
}[/sourcecode]
Then add this in your theme where you want the adsense block to appear :
[sourcecode language=”php”]
if (function_exists(‘scratch99_fromasearchengine’)) {
if (scratch99_fromasearchengine()) {
INSERT YOUR CODE HERE
}
}[/sourcecode]
Source: Smashing Magazine
Display an Advert after the first Post
Use this code in index.php to display an advert or Google Adsense after the first post :
[sourcecode language=”php”]
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); $loopcounter++; ?>
// the loop stuffs
<?php if ($loopcounter <= 1) { include (TEMPLATEPATH . ‘/ad.php’); } ?>
<?php endwhile; ?>
<?php else : ?>
<?php endif; ?>[/sourcecode]
Source: Web Designer Wall
Display Latest Posts
Use this code to display a list of your latest 5 posts, I like to use this in a footer or sidebar :
[sourcecode language=”php”]
<?php query_posts(‘showposts=5’); ?>
<ul>
<?php while (have_posts()) : the_post(); ?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php endwhile;?>
</ul>
[/sourcecode]
Source: Web Designer Wall
Show Scheduled Posts
If you have posts in upcoming que and wish to display them pubicly, use this code anywhere in your theme :
[sourcecode language=”php”]<code>
<?php query_posts(‘showposts=10&post_status=future’); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<p class><b><?php the_title(); ?></b><?php edit_post_link(‘e’,’ (‘,’)’); ?><br />
<span class="datetime"><?php the_time(‘j. F Y’); ?></span></p>
<?php endwhile; else: ?><p>No future posts scheduled.</p><?php endif; ?>
</div>[/sourcecode]
Source: Malar Vizhi
Show Most commented Posts with a thumbnail
A handy hack to use in your sidebar, your most popular posts rated by comment count. Paste the following code and change https://an-alternative-image.jpg to an image of your choice incase the post doesn’t have a thumbnail:
[sourcecode language=”php”]
<?php $popular = new WP_Query(‘orderby=comment_count&posts_per_page=5’); ?>
<?php while ($popular->have_posts()) : $popular->the_post(); ?>
<?php $justanimage = get_post_meta($post->ID, ‘Image’, true);
if ($justanimage) { ?>
<img src="<?php echo get_post_meta($post-/>ID, "Image", true); ?>" alt="<?php the_title(); ?>" />
<?php } else { ?>
<img src="https://an-alternative-image.jpg" alt="" />
<?php } ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php endwhile; ?>[/sourcecode]
Source: The Mega Mag
Display your Feedburner count as text
Simple way to display your Feedburner subscriber count in text format, replace YOUR FEED ADDRESS with your own url:
[sourcecode language=”php”]
<?php
$url = file_get_contents(‘https://feedburner.google.com/api/awareness/1.0/Get
FeedData?uri=YOUR FEED ADDRESS’);
$begin = ‘circulation="’; $end = ‘"’;
$page = $url;
$parts = explode($begin,$page);
$page = $parts[1];
$parts = explode($end,$page);
$fbcount = $parts[0];
if($fbcount == ”) { $fbcount = ‘0’; }
echo ‘<b> ‘.$fbcount.’ Subscribers’;
?>
</div>[/sourcecode]
Source: The Mega Mag
Display your Twitter Follower Count as text
Simple way to display your Feedburner subscriber count in text format, replace USERNAME with your own username.
[sourcecode language=”php”]
<?php
$twit = file_get_contents(‘https://twitter.com/users/show/USERNAME.xml’);
$begin = ‘<followers_count>’; $end = ”;
$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’;
?>
</div>[/sourcecode]
Source: The Mega Mag
Highlight Searched text in Search Results
A nice simple change that will highlight the text searched for on the search results page.
First of all open your search.php file and find the the_title() function and replace it with :
[sourcecode language=”php”]echo $title;[/sourcecode]
Now before the modified code, add this :
[sourcecode language=”php”]<?php
$title = get_the_title();
$keys= explode(" ",$s);
$title = preg_replace(‘/(‘.implode(‘|’, $keys) .’)/iu’,
‘<strong class="search-excerpt"></strong>’,
$title);
?>[/sourcecode]
Finally, add some styling in your stylesheet.css :
[sourcecode language=”php”]strong.search-excerpt { background: yellow; }[/sourcecode]
Source: Malar Vizhi
How To Separate Trackbacks from Comments
If you want to show trackbacks separately in your comments section then use the following :
Open comments.php and find the following :
[sourcecode language=”php”]<?php foreach ($comments as $comment) : ?>[/sourcecode]
After it, paste this :
[sourcecode language=”php”]<?php $comment_type = get_comment_type(); ?>
<?php if($comment_type == ‘comment’) { ?>[/sourcecode]
Now find :
[sourcecode language=”php”]<?php endforeach; /* end for each comment */ ?>[/sourcecode]
Before it, Paste :
[sourcecode language=”php”]<?php } else { $trackback = true; } /* End of is_comment statement */ ?>[/sourcecode]
That has now removed trackbacks and pingbacks, we just need to add a loop for them separately now, find the following :
[sourcecode language=”php”]<?php else : // this is displayed if there are no comments so far ?>[/sourcecode]
Before it, Paste :
[sourcecode language=”php”]<?php if ($trackback == true) { ?>
<h3>Trackbacks</h3>
<ol>
<?php foreach ($comments as $comment) : ?>
<?php $comment_type = get_comment_type(); ?>
<?php if($comment_type != ‘comment’) { ?>
<li><?php comment_author_link() ?></li>
<?php } ?>
<?php endforeach; ?>
</ol>
<?php } ?>[/sourcecode]
Source: Pro Blog Design
Add a login box to your theme
If you want to let people login from your website without going to the WordPress login page, you can paste the following code where you want the loginbox, for example in your sidebar :
[sourcecode language=”php”]
<li>
<?php global $user_ID, $user_identity, $user_level ?>
<?php if ( $user_ID ) : ?>
<h2>Control panel</h2>
<ul>
<li>Identified as <strong><?php echo $user_identity ?></strong>.
<ul>
<li><a href="<?php bloginfo(‘url’) ?>/wp-admin/">Dashboard</a></li>
<?php if ( $user_level >= 1 ) : ?>
<li><a href="<?php bloginfo(‘url’) ?>/wp-admin/post-new.php">Write an article</a></li>
<?php endif // $user_level >= 1 ?>
<li><a href="<?php bloginfo(‘url’) ?>/wp-admin/profile.php">Profile and personal options</a></li>
<li><a href="<?php bloginfo(‘url’) ?>/wp-login.php?action=logout&redirect_to=<?php echo urlencode($_SERVER[‘REQUEST_URI’]) ?>">Exit</a></li>
</ul>
</li>
</ul>
<?php elseif ( get_option(‘users_can_register’) ) : ?>
<h2>Identification</h2>
<ul>
<li>
<form action="<?php bloginfo(‘url’) ?>/wp-login.php" method="post">
<p>
<label for="log"><input type="text" name="log" id="log" value="<?php echo wp_specialchars(stripslashes($user_login), 1) ?>" size="22" /> User</label><br />
<label for="pwd"><input type="password" name="pwd" id="pwd" size="22" /> Password</label><br />
<input type="submit" name="submit" value="Send" class="button" />
<label for="rememberme"><input name="rememberme" id="rememberme" type="checkbox" checked="checked" value="forever" /> Remember me</label><br />
</p>
<input type="hidden" name="redirect_to" value="<?php echo $_SERVER[‘REQUEST_URI’]; ?>"/>
</form>
</li>
<li><a href="<?php bloginfo(‘url’) ?>/wp-register.php">Register</a></li>
<li><a href="<?php bloginfo(‘url’) ?>/wp-login.php?action=lostpassword">Recover password</a></li>
</ul>
<?php endif // get_option(‘users_can_register’) ?>
</li>
[/sourcecode]
Source: WP Designer
Exclude a category from the homepage
Really handy hack, if you wanted to use a category for news in your sidebar etc In this code, the category number excluded is 7 :
[sourcecode language=”php”]
<?php while ( have_posts() ) {
the_post();
if (is_home()) if (in_category(‘7’)) continue;
?>
[/sourcecode]
Source: Designer Daily
Exclude a category from the RSS Feed
For the same reason, you may to exclude this category from your RSS Feed, again the category excluded is 7 :
[sourcecode language=”php”]
https://www.yoururl.com/feed?cat=-7
[/sourcecode]
Source: Designer Daily
Display posts from one category in the Sidebar
Now that you have excluded the category from the homepage and feed, you can include it on its own in the sidebar with the following code :
[sourcecode language=”php”]
<?php query_posts(‘cat=7&showposts=10’); ?>
<?php while (have_posts()) : the_post(); ?> <a href="<?php the_permalink(); ?>>
<?php the_title(); ?></a><br />
<?php endwhile;?>
[/sourcecode]
Source: Designer Daily
Display an external RSS Feed anywhere in your theme
If you want to include any RSS feed in your theme, use the following :
[sourcecode language=”php”]
<?php include_once(ABSPATH.WPINC.’/rss.php’); wp_rss(‘https://example.com/external.php?type=RSS2’, 5); ?>
[/sourcecode]
Source: Designer Daily
Add a Shortcode
Shortcodes are a simple way of inserting code functions in your theme without having to type them out each time, add this to your theme functions.php :
[sourcecode language=”php”]
# Adds a shortcode called ‘hello’.
function helloworld() {
return ‘Hello World!’;
}
add_shortcode(‘hello’, ‘helloworld’);
[/sourcecode]
Then, where you want the fucntion to appear, type :
[sourcecode language=”php”]
[hello]
[/sourcecode]
Source: WP Snippets
Display “Time Ago” like Twitter
You can use this snippet for posts/pages or comments :
For Posts and Pages :
[sourcecode language=”php”]
<?php echo human_time_diff(get_the_time(‘U’), current_time(‘timestamp’)) . ‘ ago’; ?>
[/sourcecode]
For Comments :
[sourcecode language=”php”]
<?php echo human_time_diff(get_comment_time(‘U’), current_time(‘timestamp’)) . ‘ ago’; ?>
[/sourcecode]
Source: WP Snippets
Share on Facebook
Allow visitors to quickly share your post on facebook :
[sourcecode language=”php”]
<a href="https://www.facebook.com/sharer.php?u=<?php the_permalink();?>&t=<?php the_title(); ?>" title="Share on Facebook" target="blank">Share on Facebook</a>
[/sourcecode]
Source: WP Snippets
Empty the Trash Automatically
Handy little hack to auto-clear the trash, just add this to your wp-config.php file :
[sourcecode language=”php”]
define(‘EMPTY_TRASH_DAYS’, 5 );
[/sourcecode]
Source: WP Snippets
1 thought on “22 Handy WordPress Code Snippets”
Ahaa, its nice dialogue regarding this piece of writing here at this
weblog, I have read all that, so at this time me also commenting here.
Comments are closed.