wordpress Snippets for wp-config.php

Query a certain category, example is doing facebook which I do with my customers

query_posts('showposts=5&category_name=facebook');
if ( have_posts() ) : while ( have_posts() ) : the_post();
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> 
<p><?php the_content(); ?></p> 
endwhile; else:
endif;
wp_reset_query();

empty trash

define('EMPTY_TRASH_DAYS', 5 );

increase memory limit

 define('WP_MEMORY_LIMIT', '96M');

add facebook and twitter share on bottom of every 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" 
 
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');

Source: WP Recipes

email posts

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
%20share%20this%20post%20with%20you%20from%20
<?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

Don't show exact time post was modified

Instead of displaying the date that your post was posted, you can make it relative – “6 months ago” or “3 weeks ago” or whatever. Use this in your posts/comments/pages

 # For posts &amp; pages #
<?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; 
# For comments #
<?php echo human_time_diff(get_comment_time('U'), current_time('timestamp')) . ' ago'; ?> 

Source: WP Snippets

make your own help menu

Edit the Help dropdown

This could come in handy if you are creating websites for clients and you want to add extra contextual help.

 //hook loading of new page and edit page screens
add_action('load-page-new.php','add_custom_help_page'); 
add_action('load-page.php','add_custom_help_page'); 
function add_custom_help_page() { 
//the contextual help filter
add_filter('contextual_help','custom_page_help'); 
} 
function custom_page_help($help) { 
//keep the existing help copy
echo $help; 
//add some new copy
echo "<h5>Custom Features</h5>"; 
echo "<p>Content placed above the more divider will appear in column 1. Content placed below the divider will appear in column 2.</p>"; 
} 

Source: Smashing Magazine

set 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

set own branding on login

This is great for people building websites for clients who want to have their own branding all over the installation.

 
function my_custom_login_logo() { 
echo '<style type="text/css"> 
h1 a { background-image:url('.get_bloginfo('template_directory').'/images/custom-login-logo.gif) !important; } 
</style>'; 
} 
add_action('login_head', 'my_custom_login_logo'); 

Source: WP Recipes

set autosave time

WordPress’ autosave is very handy. This snippet lets you specify how often it happens. Copy to your wp-config.php

 
# Autosave interval set to 5 Minutes #
define('AUTOSAVE_INTERVAL', 300); 

Source: WP Zine

limit autosaves

I love the autosave function but I do end up with loads of post revisions. Use this to limit the number.

 
# Maximum 5 revisions #
define('WP_POST_REVISIONS', 5); 
# Disable revisions #
define('WP_POST_REVISIONS', false); 

Source: Lava 360

website under construction

Need a quick maintenance mode? Use this snippet. Just comment it out when you don’t want it switched on.

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

Source: WP Snippets

You can use Code snippets for any of the snippets below

here is where you can get code snippets

I always am updating this page

 

 

 

browser caching

This is a great snippet for speeding up your website. Paste it into .htaccess (remember to backup!)

 
## EXPIRES CACHING ##
ExpiresActive On
ExpiresByType image/jpg "access 1 year" 
ExpiresByType image/jpeg "access 1 year" 
ExpiresByType image/gif "access 1 year" 
ExpiresByType image/png "access 1 year" 
ExpiresByType text/css "access 1 month" 
ExpiresByType application/pdf "access 1 month" 
ExpiresByType text/x-javascript "access 1 month" 
ExpiresByType application/x-shockwave-flash "access 1 month" 
ExpiresByType image/x-icon "access 1 year" 
ExpiresDefault "access 2 days" 
## EXPIRES CACHING ##

Source: Thomas Griffin

small cookie banner bottom of screen

<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.0/cookieconsent.min.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.0/cookieconsent.min.js"></script>
<script>
window.addEventListener("load", function(){
window.cookieconsent.initialise({
"palette": {
"popup": {
"background": "#252e39"
},
"button": {
"background": "#14a7d0"
}
},
"theme": "edgeless"
})});
</script>

Auto Trash clean

Does what it says – set the number of days and reduce the size of your database.

 
define('EMPTY_TRASH_DAYS', 5 ); 

Source: Tutzone

cute little banner top right of site saying im proud to be the father of an autistic child - original author has disappeared. Plugin not updated in 7 years

/*
Plugin Name: Fathers with an Autistic Child Ribbon
Plugin URI: http://scottkappler.com/wp-plugins-and-more
Description: When activated, this plugin will put a small ribbon with a puzzle logo and the words "Proud Father with an Autistic Child" linking to http://www.facebook.com/Fatherswithchildrenwithautism) Facebook page on the top right corner of your website. Sponsor: RipeLocalDeals.com
Author: Scott Kappler
Version: 1.0
License: GPLv2
Author URI: http://scottkappler.com/wp-plugins-and-more
*/

function render_fathers_autism_ribbon() {
$ribbon_url = plugins_url( 'fathers_autism_ribbon.png', __FILE__ );
echo "<a target='_blank' class='fathers_autism_ribbon' href='http://www.facebook.com/Fatherswithchildrenwithautism'><img src='{$ribbon_url}' alt='Proud Father with an Autistic Child' style='position: fixed; top: 0; right: 0; z-index: 100000; cursor: pointer;' /></a>";
}
add_action( 'wp_footer', 'render_fathers_autism_ribbon' );

 

You can use this image

IE11 compatibility with oxygen

Elijah Mills says to use max width on all the text elements he provided this css snippet

Olly Cowan (from) Elijah Mills - For anyone struggling with Internet Explorer compatibility, here's the most complete CSS fix I've found so far:

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {

.ct-text-block,
.ct-headline,
.oxy-rich-text,
.ct-link-text { max-width: 100%; }
img { flex-shrink: 0; }
body * { min-height: 1px; }

}

 

Working Ticker for wordpress works on mobile and desktop, this is the one I made for Breeder Designs

<style>
.message {
width: 100%;
line-height: 50px;

color: Black;
white-space: nowrap;
overflow: hidden;
box-sizing: border-box;
}
.message p {
display: inline-block;
padding-left: 100%;
animation: marquee 10s linear infinite;
}
@keyframes marquee {
0% { transform: translate(0, 0); }
100% { transform: translate(-100%, 0); }
}</style>

<div class="message">
<p>
<font style="font-family: julius sans one;color: #F0F5FA;font-size:30px;font-weight:600">We Have Specials on Some Breeds and Species. Contact us for details.</font></p>
</div>

Sridhar Katakam
This dude is amazing not only does he have great knowledge of wordpress itself
he also provides some nifty plugins for oxygen.

How to tell SEOPress to analyze Oxygen’s Content

add_filter( 'seopress_content_analysis_content', 'sp_content_analysis_content', 10, 2 );
/**
 * Filter the analyzed content to add content from Oxygen editor.
 * @param  string $content Current content in the WordPress editor.
 * @param  int $id      ID of the current entry.
 * @return string          Modified content.
 */
function sp_content_analysis_content( $content, $id ) {

    // HTML of Oxygen's content.
    $cf = do_shortcode( get_post_meta( $id, 'ct_builder_shortcodes', true ) );

    return $content . $cf;

}

Set it to run only in the admin.

That’s it!

Credit: Jan Raap.

Reference: https://wordpress.org/support/topic/it-doesnt-recognize-oxygen-texts/

Shortcode

There might be times when you want to associate different shortcodes with different posts and have these run on the frontend.

Example:

Let’s say you’ve created a custom field called shortcode and in Post A, set as its value and in Post B, .

Here’s the PHP code to execute these:


$shortcode = get_post_meta( get_the_ID(), 'shortcode', true );

echo do_shortcode( "{$shortcode}" );

If you want to enter just the name of the slider (in this example) for the custom field’s value like this: web-product-light-hero3 and photography-carousel5,

the code will then become:


$shortcode = get_post_meta( get_the_ID(), 'shortcode', true );

echo do_shortcode( "" );

Update: When the custom fields were created with Toolset, for some reason get_post_meta() isn’t working during my testing.

So use


$shortcode = types_render_field( 'shortcode', array() );

instead of


$shortcode = get_post_meta( get_the_ID(), 'shortcode', true );

Javascript counter countdown

// Set the date we're counting down to
var countDownDate = new Date("Nov 23, 2018 00:00:00").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get todays date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Display the result in the element with id="headline-63-11"
  document.getElementById("headline-63-11").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";

  // If the count down is finished, write some text 
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("headline-63-11").innerHTML = "EXPIRED";
  }
}, 1000);

Snippets to protect you and your clients Source: https://speckyboy.com/

Settings I use with custom css

@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;
}
}
.single .thumbnail { text-align: center; }
.single .thumbnail img { width: 408px !important; }

Remove WordPress Posts Columns

function remove_post_columns($defaults) {
  unset($defaults['comments']);
  return $defaults;    
} 
add_filter('manage_posts_columns', 'remove_post_columns');

Remove WordPress Pages Columns

function remove_pages_columns($defaults) {
  unset($defaults['comments']); 
  return $defaults;    
} 
add_filter('manage_pages_columns', 'remove_pages_columns');

Remove WordPress Meta-Boxes from Posts & Pages Editor Screens

Publishing posts and pages are more than likely key to your clients business and probably the main reason you chose WordPress for them in the first place. To help avoid any confusion from within the posts/pages editor screens it could be helpful to remove unused meta-boxes (custom fields, recent comments, post tags…).

Paste this into your functions.php and edit as required:

function remove_extra_meta_boxes() {
remove_meta_box( 'postcustom' , 'post' , 'normal' ); // custom fields for posts
remove_meta_box( 'postcustom' , 'page' , 'normal' ); // custom fields for pages
remove_meta_box( 'postexcerpt' , 'post' , 'normal' ); // post excerpts
remove_meta_box( 'postexcerpt' , 'page' , 'normal' ); // page excerpts
remove_meta_box( 'commentsdiv' , 'post' , 'normal' ); // recent comments for posts
remove_meta_box( 'commentsdiv' , 'page' , 'normal' ); // recent comments for pages
remove_meta_box( 'tagsdiv-post_tag' , 'post' , 'side' ); // post tags
remove_meta_box( 'tagsdiv-post_tag' , 'page' , 'side' ); // page tags
remove_meta_box( 'trackbacksdiv' , 'post' , 'normal' ); // post trackbacks
remove_meta_box( 'trackbacksdiv' , 'page' , 'normal' ); // page trackbacks
remove_meta_box( 'commentstatusdiv' , 'post' , 'normal' ); // allow comments for posts
remove_meta_box( 'commentstatusdiv' , 'page' , 'normal' ); // allow comments for pages
remove_meta_box('slugdiv','post','normal'); // post slug
remove_meta_box('slugdiv','page','normal'); // page slug
remove_meta_box('pageparentdiv','page','side'); // Page Parent
}
add_action( 'admin_menu' , 'remove_extra_meta_boxes' );

Restrict WordPress Admin Menu Items Based on Username

function remove_menus()
{
    global $menu;
    global $current_user;
    get_currentuserinfo();

    if($current_user->user_login == 'clients-username')
    {
        $restricted = array(__('Posts'),
                            __('Media'),
                            __('Links'),
                            __('Pages'),
                            __('Comments'),
                            __('Appearance'),
                            __('Plugins'),
                            __('Users'),
                            __('Tools'),
                            __('Settings')
        );
        end ($menu);
        while (prev($menu)){
            $value = explode(' ',$menu[key($menu)][0]);
            if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
        }// end while

    }// end if
}
add_action('admin_menu', 'remove_menus');

Disable Submenus from the WordPress Admin Panel

function remove_submenus() {
  global $submenu;
    unset($submenu['index.php'][10]); // Removes 'Updates'.
    unset($submenu['themes.php'][5]); // Removes 'Themes'.  
    unset($submenu['options-general.php'][15]); // Removes 'Writing'.
    unset($submenu['options-general.php'][25]); // Removes 'Discussion'.       
}
add_action('admin_menu', 'remove_submenus');

Disable Top-Level Menus from the WordPress Admin Panel

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');

Disabling WordPress Theme Changing

add_action( 'admin_init', 'slt_lock_theme' );
function slt_lock_theme() {
	global $submenu, $userdata;
	get_currentuserinfo();
	if ( $userdata->ID != 1 ) {
		unset( $submenu['themes.php'][5] );
		unset( $submenu['themes.php'][15] );
	}
}

Disabling WordPress Plugin Deactivation

add_filter( 'plugin_action_links', 'slt_lock_plugins', 10, 4 );
function slt_lock_plugins( $actions, $plugin_file, $plugin_data, $context ) {
	// Remove edit link for all
	if ( array_key_exists( 'edit', $actions ) )
		unset( $actions['edit'] );
	// Remove deactivate link for crucial plugins
	if ( array_key_exists( 'deactivate', $actions ) && in_array( $plugin_file, array(
		'slt-custom-fields/slt-custom-fields.php',
		'slt-file-select/slt-file-select.php',
		'slt-simple-events/slt-simple-events.php',
		'slt-widgets/slt-widgets.php'
	)))
		unset( $actions['deactivate'] );
	return $actions;
}
SNIPPETS FOR WORDPRESS

remind auto close time on comments

To prevent spammers from flooding old articles with useless comments you can set WordPress to close comments after a certain number of days:
close-comments
It might be surprising for some users if the comments are closed automatically so it might be a good idea to inform them about the remaining time.

add_action( 'comment_form_top', 'topic_closes_in' );

function topic_closes_in() {
    global $post;
    if ($post->comment_status == 'open') {
        $close_comments_days_old = get_option( 'close_comments_days_old' );
        $expires = strtotime( "{$post->post_date_gmt} GMT" ) +  $close_comments_days_old * DAY_IN_SECONDS;
        printf( __( '(This topic will automatically close in %s. )', 'domain' ),  human_time_diff( $expires ));
    }
}

Highlight search terms

This is a nice one. Power up your search functionality by highlighting the search term in the results.
Open search.php and find the the_title() function
Replace with:

 
echo $title; 

Above the modified line add:

 
<?php 
<span style="white-space: pre;"> </span>$title <span style="white-space: pre;"> </span>= get_the_title(); 
<span style="white-space: pre;"> </span>$keys= explode(" ",$s); 
<span style="white-space: pre;"> </span>$title <span style="white-space: pre;"> </span>= preg_replace('/('.implode('|', $keys) .')/iu',
<span style="white-space: pre;"> </span>'<strong class="search-excerpt">\0</strong>',
<span style="white-space: pre;"> </span>$title); 
?> 

Add the following to your style.css. Add:

 
strong.search-excerpt { background: yellow; } 

Source: WP Recipes

Disable WordPress Search

 
function fb_filter_query( $query, $error = true ) { 
 
if ( is_search() ) { 
$query->is_search = false; 
$query->query_vars[s] = false; 
$query->query[s] = false; 
// to error
>if ( $error == true ) 
$query->is_404 = true; 
} 
} 
add_action( 'parse_query', 'fb_filter_query' ); 
add_filter( 'get_search_form', create_function( '$a', "return null;" ) ); 

Source: WP Engineer

Pagination

Want pagination at the bottom of your blog? Insert this into your 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.
Source: WPEngineer

Google Analytics Without Editing Theme

Ever update your parent theme and then realise a few weeks later that you haven’t added your Google Analytics tracking code? All those stats, lost! Add your tracking code to your functions instead:

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

Add Custom User Contact Info

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) { 
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> 

Source: Thomas Griffin

register jquery right way

WordPress comes with many bundles JavaScript libraries like jQuery or jQuery UI.
So plugins and themes doesn't need to bundle these libraries again, instead, they can use the WP_Scripts API.

The registration is controlled by the function wp_default_scripts() in /wp-includes/script-loader.php.

/**
 * Register all WordPress scripts.
 *
 * @since 2.6.0
 *
 * @param object $scripts WP_Scripts object.
 */
function wp_default_scripts( &$scripts ) {
// […]
	$scripts->add( 'colorpicker', "/wp-includes/js/colorpicker$suffix.js", array('prototype'), '3517m' );

	$scripts->add( 'editor', "/wp-admin/js/editor$suffix.js", array('utils','jquery'), false, 1 );
// […]
	// not used in core, replaced by Jcrop.js
	$scripts->add( 'cropper', '/wp-includes/js/crop/cropper.js', array('scriptaculous-dragdrop') );

	// jQuery
	$scripts->add( 'jquery', '/wp-includes/js/jquery/jquery.js', array(), '1.7.2' );

	// full jQuery UI
	$scripts->add( 'jquery-ui-core', '/wp-includes/js/jquery/ui/jquery.ui.core.min.js', array('jquery'), '1.8.20', 1 );
	$scripts->add( 'jquery-effects-core', '/wp-includes/js/jquery/ui/jquery.effects.core.min.js', array('jquery'), '1.8.20', 1 );
// […]
}

As you can see, WP_Dependencies->add() expects the following arguments: The name, the path, the dependencies, the version and last but not least the argument to enqueue the script either in header or footer. Same as for wp_register_script() or wp_enqueue_script().

Now you should have noticed that the jQuery registration doesn't have the last argument, which means the script will be enqueued in header. With the help of a filter inside the wp_default_scripts() function we can change this.
In practice:

<?php
/**
 * Plugin Name: Enqueue jQuery in Footer
 * Version:     0.0.1
 * Plugin URI:  http://wpgrafie.de/836/
 * Description: Prints jQuery in footer on front-end.
 * Author:      Dominik Schilling
 * Author URI:  http://wpgrafie.de/
 */
function ds_enqueue_jquery_in_footer( &$scripts ) {
	 
	if ( ! is_admin() )
		$scripts->add_data( 'jquery', 'group', 1 );
}
add_action( 'wp_default_scripts', 'ds_enqueue_jquery_in_footer' );

This a really clean and nice way. No need of deregister and register functions.

Of course, you should test if this breaks any functionality, especially when you are using plugins/scripts which hasn’t set dependencies correctly.

Breadcrumbs without a plugin

Create those breadcrumb trails without the help of a plugin. Insert this into 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(); ?>

Source: WP Snippets

Edit Navigation Output

Want more control over the navigation output? This is a great snippet for it. Place this in your functions.php file and edit the PHP for the results you want.

 
class description_walker extends Walker_Nav_Menu
{ 
function start_el(&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;$output, $item, $depth, $args) 
{ 
 
global $wp_query; 
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; 
$class_names = $value = ''; 
$classes = empty( $item->classes ) ? array() : (array) $item->classes; 
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ); 
$class_names = '' : '"'; 
$output .= $indent . '
<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>'; 
$attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : ''; 
$attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : ''; 
$attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : ''; 
$attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : ''; 
 
if($depth != 0) 
{ 
$description = $append = $prepend = ""; 
} 
$item_output = $args->before; 
$item_output .= '<a' . $attributes . '>'; 
$item_output .= $args->link_before .$prepend.apply_filters( 'the_title', $item->title, $item->ID ).$append; 
$item_output .= $description.$args->link_after; 
$item_output .= '</a>'; 
$item_output .= $args->after; 
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); 
} 
} 

Source: Lava 360

Remove Title from WordPress Menu Links

 function my_menu_notitle( $menu ){ 
 
return $menu = preg_replace('/ title=\"(.*?)\"/', '', $menu ); 
} 
add_filter( 'wp_nav_menu', 'my_menu_notitle' ); 
add_filter( 'wp_page_menu', 'my_menu_notitle' ); 
add_filter( 'wp_list_categories', 'my_menu_notitle' ); 

Source: Dynamic WP

Automatically Add a Search Box to Your Nav Menu

 
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; 
} 

Source: WP Recipes

WordPress Relative Date

 # For posts &amp; pages #
<?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; 
# For comments #
<?php echo human_time_diff(get_comment_time('U'), current_time('timestamp')) . ' ago'; ?> 

Source: WP Snippets

Remove Menus in WordPress Dashboard

 
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'); 

Source: WPRecipes

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>';
    else
        return '<a href="'.$m[1].'" target="_blank">'.$m[2].'</a>';
    }, $content);
return $content;
}
add_filter('the_content', 'add_nofollow_content');

maintenance mode

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

Source: WP Snippets

Leverage Browser Caching using .htaccess

## EXPIRES CACHING ##
ExpiresActive On
ExpiresByType image/jpg "access 1 year" 
ExpiresByType image/jpeg "access 1 year" 
ExpiresByType image/gif "access 1 year" 
ExpiresByType image/png "access 1 year" 
ExpiresByType text/css "access 1 month" 
ExpiresByType application/pdf "access 1 month" 
ExpiresByType text/x-javascript "access 1 month" 
ExpiresByType application/x-shockwave-flash "access 1 month" 
ExpiresByType image/x-icon "access 1 year" 
ExpiresDefault "access 2 days" 
## EXPIRES CACHING ##

Detect Mobile Users

include('mobile_device_detect.php'); 
$mobile = mobile_device_detect(); 
 
if ($mobile==true) { 
header( 'Location: http://your-website.com/?theme=Your_Mobile_Theme' ) ; 
}

Simpler Login Address

 
RewriteRule ^login$ http://yoursite.com/wp-login.php [NC,L] 

Source: Digging into WordPress

Limit Post Revisions

 
# Maximum 5 revisions #
define('WP_POST_REVISIONS', 5); 
# Disable revisions #
define('WP_POST_REVISIONS', false); 

Source: Lava 360

Set Autosave time

 
# Autosave interval set to 5 Minutes #
define('AUTOSAVE_INTERVAL', 300); 

Source: WP Zine

Customize WordPress Login Logo Without a Plugin

 
function my_custom_login_logo() { 
echo '<style type="text/css"> 
h1 a { background-image:url('.get_bloginfo('template_directory').'/images/custom-login-logo.gif) !important; } 
</style>'; 
} 
add_action('login_head', 'my_custom_login_logo'); 

Source: WP Recipes

Change Admin Logo

 
function custom_admin_logo() { 
echo '<style type="text/css"> 
#header-logo { background-image: url('.get_bloginfo('template_directory').'/images/admin_logo.png) !important; } 
</style>'; 
} 
add_action('admin_head', 'custom_admin_logo'); 

Source: WP Snippets

Change Footer Text in WP Admin

 
function remove_footer_admin () { 
echo 'Siobhan is Awesome. Thank you <a href="http://wordpress.org">WordPress</a> for giving me this filter.'; 
} 
add_filter('admin_footer_text', 'remove_footer_admin'); 

Source: Lava360

Add Favicon

 
<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

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;
}
}

WORDPRESS SNIPPETS FOUND ON THE WEB

google analytics

<?php 
 
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()

 
delete_comment_link(get_comment_ID()); 

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("
SELECT
YEAR(min(post_date_gmt)) AS firstdate,
YEAR(max(post_date_gmt)) AS lastdate
FROM
$wpdb->posts
WHERE
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) { 
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> 

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): 
setup_postdata($post); 
$counts++; 
add_post_meta($post->ID, 'incr_number', $counts, true); 
update_post_meta($post->ID, 'incr_number', $counts); 
 
endforeach; 
 
endif; 
} 
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> 
</div> 
<?php endwhile; else: ?><p>No future events scheduled.</p><?php endif; ?> 
</div> 

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; 
get_currentuserinfo(); 
$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
%20share%20this%20post%20with%20you%20from%20
<?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" 
 
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');

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
 
unlink($uploaded_image_location); 
// rename the large image
 
rename($large_image_location,$uploaded_image_location); 
// update image metadata and return them
 
$image_data['width'] = $image_data['sizes']['large']['width']; 
$image_data['height'] = $image_data['sizes']['large']['height']; 
unset($image_data['sizes']['large']); 
 
return $image_data; 
} 
add_filter('wp_generate_attachment_metadata','replace_uploaded_image'); 

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.

 
<?php 
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;
&lt;?php
          $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;;
          }
?&gt;

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')
        return;
    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);
    if(!empty($user->user_login))
        $username = $user->user_login;
    return $username;
}
add_action('wp_authenticate','login_with_email_address');

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

add_action('media_buttons','add_sc_select',11);
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){
            if(!in_array($key,$exclude)){
            $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(document).ready(function(){
           jQuery("#sc_select").change(function() {
                          send_to_editor(jQuery("#sc_select :selected").val());
                          return false;
                });
        });
        </script>';
}

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"';
else
$class = '';
$homeMenuItem = '<li '="" .="" $class="">' .
$args->before .
'<a href="' . home_url( '/' ) . '" title="Home">' .
$args->link_before .
'Home' .
$args->link_after .
'</a>' .
$args->after .
'</li>';
$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