WordPress snippets to work with social networks

Automatically add Open Graph to your posts

Open Graph is a protocol created by facebook which allow you to make your content easily recognizable by social networks.

To automatically add Open Graph metadata to your posts, let’s start by pasting the following code snippet into your functions.php file.

function wptuts_opengraph_for_posts() {
    if ( is_singular() ) {
        global $post;
        setup_postdata( $post );
        $output = '<meta property="og:type" content="article" />' . "\n";
        $output .= '<meta property="og:title" content="' . esc_attr( get_the_title() ) . '" />' . "\n";
        $output .= '<meta property="og:url" content="' . get_permalink() . '" />' . "\n";
        $output .= '<meta property="og:description" content="' . esc_attr( get_the_excerpt() ) . '" />' . "\n";
        if ( has_post_thumbnail() ) {
            $imgsrc = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
            $output .= '<meta property="og:image" content="' . $imgsrc[0] . '" />' . "\n";
        }
        echo $output;
    }
}
add_action( 'wp_head', 'wptuts_opengraph_for_posts' );

Then, open your header.php and replace the <html> tag by this:

<html <?php language_attributes(); ?> prefix="og: http://ogp.me/ns#">

Source: http://wp.tutsplus.com/articles/general/5-essential-tips…

Create a Pinterest “pin it” button for your blog

Pinterest is a website where people can create and share bookmarks of interesting stuff they find among the web. Like Facebook or Twitter, a Pinterest button can be added to your posts in order to make it easy for people to add your content to the network.

The first thing to do is to paste the following snippet where you’d like the “Pin It” button to be displayed. Note that this code must be inserted within the loop.

<a href="http://pinterest.com/pin/create/button/?url=<?php the_permalink(); ?>&media=<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail' ); echo $thumb['0']; ?>&description=<?php the_title(); ?>" class="pin-it-button" count-layout="horizontal">Pin It</a>

Once done, open your footer.php file and add the Pinterest JavaScript code:

<script type="text/javascript" src="http://assets.pinterest.com/js/pinit.js"></script>

Source: http://www.marketingtechblog.com/wordpress-pinterest-button/

Display your latest tweet on your blog without using a plugin

Many plugins are available if you’re looking for a way to display your latest tweet on your blog. But you don’t really need to install a plugin for that.

Simply paste the following code anywhere in your theme files, where you want the tweets to be displayed. Don’t forget to update the code with your username on line 3. Max items to display can be defined on line 4.

<?php
include_once(ABSPATH . WPINC . '/feed.php');
$rss = fetch_feed('https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=catswhocode');
$maxitems = $rss->get_item_quantity(3);
$rss_items = $rss->get_items(0, $maxitems);
?>

<ul>
<?php if ($maxitems == 0) echo '<li>No items.</li>';
else
// Loop through each feed item and display each item as a hyperlink.
foreach ( $rss_items as $item ) : ?>
<li>
<a href='<?php echo $item->get_permalink(); ?>'>
<?php echo $item->get_title(); ?>
</a>
</li>
<?php endforeach; ?>
</ul>

Source: http://wp.smashingmagazine.com/2012/01/19/facebook-twitter-google-wordpress/

Add a Google+ button to your posts

Google+ is a social network from Google, and it’s becoming more popular day by day. To add a google+ button to your posts, simply open your functions.php file and paste the following code in it:

add_filter('the_content', 'wpr_google_plusone');
function wpr_google_plusone($content) {
	$content = $content.'<div class="plusone"><g:plusone size="tall" href="'.get_permalink().'"></g:plusone></div>';
	return $content;
}
add_action ('wp_enqueue_scripts','wpr_google_plusone_script');
function wpr_google_plusone_script() {
	wp_enqueue_script('google-plusone', 'https://apis.google.com/js/plusone.js', array(), null);
}

Source: http://spyrestudios.com/17-time-saving-code-snippets-for-wordpress-developers/

Display your lastest Google+ update

If you’re a Google+ user, you might want to display your latest Google+ update. To do so, paste the code below where you want to display your latest Google+ update. Just don’t forget to put your Google+ ID on line 3.

<?php
	include_once(ABSPATH.WPINC.'/rss.php');
	$googleplus = fetch_feed("http://plusfeed.appspot.com/103329092193061943712"); // Replace 103329092193061943712 by your own ID
	echo '<a href="';
	echo $googleplus->items[0]['link']; echo '">';
	echo $googleplus->items[0]['summary'];
	echo '';
?>

Source: http://www.geekeries.fr/snippet/afficher-mise-a-jour-google-plus

Automatically add Twitter and Facebook buttons to your posts

Facebook and Twitter are the two most popular social networks, and they can provide lots of traffic to your website. In order to make it easy for people to share your posts on Twitter and Facebook, paste this code into your functions.php file and save it. It will display both Facebook and Twitter buttons, like those you can see at the bottom of this post.

function share_this($content){
    if(!is_feed() && !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: http://www.wprecipes.com/automatically-add-twitter-and-facebook-buttons-to-your-posts

Display your favorite tweets with WordPress

Paste this code where you want your favorite tweets to be displayed. Don’t forget to update your favorite feed url on line 3.

<?php
    include_once(ABSPATH . WPINC . '/feed.php');
    $rss = fetch_feed('http://twitter.com/favorites/793830.rss');
    $maxitems = $rss->get_item_quantity(3); 
    $rss_items = $rss->get_items(0, $maxitems);
?>

<ul>
    <?php if ($maxitems == 0) echo '<li>No items.</li>';
    else
    // Loop through each feed item and display each item as a hyperlink.
    foreach ( $rss_items as $item ) : ?>
    <li>
        <a href='<?php echo $item->get_permalink(); ?>'>
            <?php echo $item->get_title(); ?>
        </a>
    </li>
    <?php endforeach; ?>
</ul>

Source: http://css-tricks.com/snippets/wordpress/display-rss-in-wordpress/

Display how many times a post has been shared on twitter

If you want to display how many times a post has been shared on Twitter, simply paste the function below into your functions.php file:

function readTwitterShares($url) {
 $s = file_get_contents("http://urls.api.twitter.com/1/urls/count.json".
   "?callback=?&url=".urlencode($url));
   preg_match("#(\"count\"):([0-9]*)#",$s,$ar);
   return isset($ar[2]) ? $ar[2] : 0;
}

Then use the following code within the loop to display how many times the current post has been shared on Twitter:

echo readTwitterShares(get_permalink());

Source: http://www.barattalo.it/2012/10/19/how-many-times-a-web-link-has-been-shared…

Add Twitter and Facebook info fields

By default, WordPress allows you to add various contact info as such as Jabber, AIM and Yahoo Messenger. But there’s no way to add your Twitter and Facebook info. Here’s a handy code snippet to remove the mostly useless YIM, AIM and Jabber and add Twitter and Facebook info instead.

This code goes to your functions.php file.

function new_contactmethods( $contactmethods ) {
    $contactmethods['twitter'] = 'Twitter'; // Add Twitter
    $contactmethods['facebook'] = 'Facebook'; // Add Facebook
    unset($contactmethods['yim']); // Remove YIM
    unset($contactmethods['aim']); // Remove AIM
    unset($contactmethods['jabber']); // Remove Jabber

    return $contactmethods;
}
add_filter('user_contactmethods','new_contactmethods',10,1);  

Source: http://wp-snippets.com/addremove-contact-info-fields

How to use Open Graph to make your content easily recognizable by social networks

Simply paste the code below into your functions.php file. The snippet will automatically add the Open Graph metadata to the <head> section of your pages.

function wptuts_opengraph_for_posts() {
    if ( is_singular() ) {
        global $post;
        setup_postdata( $post );
        $og_type = '<meta property="og:type" content="article" />' . "\n";
        $og_title = '<meta property="og:title" content="' . esc_attr( get_the_title() ) . '" />' . "\n";
        $og_url = '<meta property="og:url" content="' . get_permalink() . '" />' . "\n";
        $og_description = '<meta property="og:description" content="' . esc_attr( get_the_excerpt() ) . '" />' . "\n";
        if ( has_post_thumbnail() ) {
            $imgsrc = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
            $og_image = '<meta property="og:image" content="' . $imgsrc[0] . '" />' . "\n";
        }
        echo $og_type . $og_title . $og_url . $og_description . $og_image;
    }
}
add_action( 'wp_head', 'wptuts_opengraph_for_posts' );

In order to make your blog fully compliant with the Open Graph protocol, you also have to edit your header.php file and replace the <html> tag by the following:

<html <?php language_attributes(); ?> prefix="og: http://ogp.me/ns#">

Thanks to WP Tuts for the tip!

How to create a Pinterest “pin it” button for your WordPress blog

The first thing to do is to paste the following snippet where you’d like the “Pin It” button to be displayed. Note that this code must be inserted within the loop.

<a href="http://pinterest.com/pin/create/button/?url=<?php the_permalink(); ?>&media=<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail' ); echo $thumb['0']; ?>&description=<?php the_title(); ?>" class="pin-it-button" count-layout="horizontal">Pin It</a>

Once done, open your footer.php file and add the pinterest JavaScript code:

<script type="text/javascript" src="http://assets.pinterest.com/js/pinit.js"></script>

Thanks to Douglas Karr for the cool code!

jQuery Slider Shock giveaway: 5 licenses to win!

jQuery Slider Shock is the most complete and awesome slider for jQuery and WordPress ever. It has more than 30 effects and skins, allows external data sources such as Instagram, Flickr, Youtube, RSS, among others, fixed or responsive width (mobile ready), adjustable size, several instances of the slider in a same page, several thumbnail positions, customizable design aspect (colors, fonts, placements, html captions) and a lot more.

How to enter the contest?

That’s pretty simple: Simply copy the following sentence and tweet it:

I’m in the run to win a full multisite license of Slider Shock. The best#jquery #wordpress #plugin. http://bit.ly/T7EtjU

Then,paste the link to your tweet in a comment below. On November 22, 2012, 5 people will be randomly chosen and will receive a premium multisite license. Winners will be able to chose from the jQuery, WordPress or Bundle versions.

Good luck!

How to automatically hide email adresses from spambots on your WordPress blog

Paste the following code into your functions.php file. Once you saved the file, the code will filter content and widget content to hide all e-mails from spambots.

function security_remove_emails($content) {
    $pattern = '/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})/i';
    $fix = preg_replace_callback($pattern,"security_remove_emails_logic", $content);

    return $fix;
}
function security_remove_emails_logic($result) {
    return antispambot($result[1]);
}
add_filter( 'the_content', 'security_remove_emails', 20 );
add_filter( 'widget_text', 'security_remove_emails', 20 );

Thanks to Stian Jacobsen for submitting this tip!

Making a website responsive in 3 easy steps

1 – The layout

When building a responsive website, or making responsive an existing site, the first element to look at is the layout. When I build responsive websites, I always start by creating a non-responsive layout, fixed at the default size. For example, CatsWhoCode.com default width is 1100px. When I’m pleased with the non-responsive version, I add media queries and slight changes to my code to make the code responsive. It’s way easier to focus on one task at a time.

When you’re done with your non-responsive website, the first thing to do is to paste the following lines within the <head> and </head> tags on your html page. This will set the view on all screens at a 1×1 aspect ratio and remove the default functionality from iPhones and other smartphone browsers which render websites at full-view and allow users to zoom into the layout by pinching.

<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="HandheldFriendly" content="true">

It’s now time to add some media queries. According to the W3C site, a media query consists of a media type and zero or more expressions that check for the conditions of particular media features. By using media queries, presentations can be tailored to a specific range of output devices without changing the content itself. In other words, media queries allows your website to look good on all kinds of displays, from smartphones to big screens.

Media queries depends of your website layout, so it’s kinda difficult for me to provide you a ready to use code snippet. However, the code below is a good starting point for most websites. In this example, #primary is the main content area, and #secondary the sidebar.

By having a look at the code, you can see that I defined two sizes: The first have a maximum width of 1060px and is optimized for tablet landscape display. #primary occupies 67% of its parent container, and #secondary 30%, plus a 3% left margin.

The second size is designed for tablet portrait and smaller sizes. Due to the small sizes of smartphones screens, I decided to give #primary a 100% width. #secondary also have a 100% width, and will be displayed below #primary.

As I already said, you’ll probably have to adapt this code a bit to fit the specific needs of your website. Paste it on your site .css file.

/* Tablet Landscape */
@media screen and (max-width: 1060px) {
    #primary { width:67%; }
    #secondary { width:30%; margin-left:3%;}  
}

/* Tabled Portrait */
@media screen and (max-width: 768px) {
    #primary { width:100%; }
    #secondary { width:100%; margin:0; border:none; }
}

Once done, let’s see how responsive your layout is. To do so, I use this awesome tool created by Matt Kersley.

2 – Medias

A responsive layout is the first step to a fully responsive website. Now, let’s focus on a very important aspect of a modern website: medias, such as videos or images.

The CSS code below will ensure that your images will never be bigger than their parent container. It’s super simple and it works for most websites. Please note that the max-width directive is not recognized by older browsers such as IE6. In order to work, this code snippet have to be inserted into your CSS stylesheet.

img { max-width: 100%; }

Although the technique above is efficient, sometimes you may need to have more control over images and display a different image according to the client display size.

Here is a technique developed by Nicolas Gallagher. Let’s start with the html:

<img src="image.jpg"
     data-src-600px="image-600px.jpg"
     data-src-800px="image-800px.jpg"
     alt="">

As you can see, we used the data-* attribute to store replacement images urls. Now, let’s use the full power of CSS3 to replace the default image by one of the specified replacement images if the min-device-width condition is matched:

@media (min-device-width:600px) {
    img[data-src-600px] {
        content: attr(data-src-600px, url);
    }
}

@media (min-device-width:800px) {
    img[data-src-800px] {
        content: attr(data-src-800px, url);
    }
}

Impressive, isn’t it? Now let’s have a look to another very important media in today’s websites, videos.

As most websites are using videos from third parties sites such as YouTube or Vimeo, I decided to focus on the elastic video technique by Nick La. This technique allows you to make embedded videos responsive.

The html:

<div class="video-container">
	<iframe src="http://player.vimeo.com/video/6284199?title=0&byline=0&portrait=0" width="800" height="450" frameborder="0"></iframe>
</div>

And now, the CSS:

.video-container {
	position: relative;
	padding-bottom: 56.25%;
	padding-top: 30px;
	height: 0;
	overflow: hidden;
}

.video-container iframe,  
.video-container object,  
.video-container embed {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
}

Once you applied this code to your website, embedded videos are now responsive.

3 – Typography

The last step of this tutorial is definitely important, but it is often neglected by developers when it comes to responsive websites: Typography.

Until now, most developer (including myself!) used pixels to define font sizes. While pixels are ok when your website have a fixed width, a responsive website should have a responsive font. Indeed, a responsive font size should be related to its parent container width, so it can adapt to the screen of the client.

The CSS3 specification included a new unit named rems. They work almost identically to the em unit, but are relative to the html element, which make them a lot easier to use than ems.

As rems are relative to the html element, don’t forget to reset html font size:

html { font-size:100%; } 

Once done, you can define responsive font sizes as shown below:

@media (min-width: 640px) { body {font-size:1rem;} } 
@media (min-width:960px) { body {font-size:1.2rem;} } 
@media (min-width:1100px) { body {font-size:1.5rem;} } 

Please note that the rem unit is not recognized by older browers, so don’t forget to implement a fallback.
That’s all for today – I hope you enjoyed this tutorial!

Awesome jQuery snippets to work with forms

Disable “enter” key in your forms

If you want to prevent visitors to accidentally submit your form by hitting the “enter” key, you can use this snippet to disable the use of the “enter” key in your forms.

$("#form").keypress(function(e) {
  if (e.which == 13) {
    return false;
  }
});

Source: http://www.catswhocode.com/blog/10-awesome-jquery-snippets

Clear form data

Need to clear all form data? Here’s a handy function to do it.

function clearForm(form) {
  // iterate over all of the inputs for the form
  // element that was passed in
  $(':input', form).each(function() {
    var type = this.type;
    var tag = this.tagName.toLowerCase(); // normalize case
    // it's ok to reset the value attr of text inputs,
    // password inputs, and textareas
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = "";
    // checkboxes and radios need to have their checked state cleared
    // but should *not* have their 'value' changed
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    // select elements need to have their 'selectedIndex' property set to -1
    // (this works for both single and multiple select elements)
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

Source: http://www.jquery4u.com/forms/jquery-function-clear-form-data/#.UI02J2knDF8

Find is a checkbox is checked

Find out if a single checkbox is checked or not. The function will returns true or false:

$('#checkBox').attr('checked');

Source: http://jquery-howto.blogspot.be/2008/12/how-to-check-if-checkbox-is-checked.html

Enable/Disable form elements

Want to make your forms more user-friendly? Then you can enable or disable form elements such as the submit button. For example, you can have it disabled by default and enable it only if the form has been properly filled by the visitor.

$("#submit-button").attr("disabled", true);

And to re-enable a previously disabled input:

$("#submit-button").removeAttr("disabled");

Source: http://css-tricks.com/snippets/jquery/disable-re-enable-inputs/

Enable submit button if text entered

Here’s a variant of the above snippet, this time allowing you to automatically enable the submit button if some text is entered in a #username input field.

$('#username').keyup(function() {
    $('#submit').attr('disabled', !$('#username').val()); 
});

Source: http://cakebaker.42dh.com/2009/01/13/enabling-submit-button-if-text-entered/

Submit form programmatically

Super simple but definitely useful: Here’s how to submit a form programmatically using jQuery.

$("#myform").submit();

Source: http://www.jquery4u.com/snippets/jquery-simulate-form-submit/

Prevent multiple submit of your form

Multiple submissions of the same form is definitely one of the most common problem seen when working with web forms. Here’s a super useful piece of code to prevent multiple submissions of the same form.

$(document).ready(function() {
  $('form').submit(function() {
    if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
      jQuery.data(this, "disabledOnSubmit", { submited: true });
      $('input[type=submit], input[type=button]', this).each(function() {
        $(this).attr("disabled", "disabled");
      });
      return true;
    }
    else
    {
      return false;
    }
  });
});

Source: http://damienalexandre.fr/post/2009/08/02/jQuery-eviter-la-soumission-multiple-d-un-formulaire

Highlight related label when input in focus

Another way to make your form easier to fill for your visitors: Highlight related label when input in focus. Here’s some jQuery goodness to help.

$("form :input").focus(function() {
  $("label[for='" + this.id + "']").addClass("labelfocus");
}).blur(function() {
  $("label").removeClass("labelfocus");
});

Source: http://css-tricks.com/snippets/jquery/highlight-related-label-when-input-in-focus/

Dynamically add form elements

If you need to dynamically add form elements, the snippet below is a simple way to do it.

//change event on password1 field to prompt new input
$('#password1').change(function() {
        //dynamically create new input and insert after password1
        $("#password1").append("<input type='text' name='password2' id='password2' />");
});

Source: http://www.jquery4u.com/forms/jquery-dynamically-add-form-elements/

Auto-populating select boxes using Ajax & JSON

When building an interactive form, it is very useful to be able to get some data with ajax and use it to populate a select element.
The following snippet shows how to get data from a php file named select.php (line 3) and populate a select element with it.

$(function(){
  $("select#ctlJob").change(function(){
    $.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
      var options = '';
      for (var i = 0; i < j.length; i++) {
        options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
      }
      $("select#ctlPerson").html(options);
    })
  })
})

Source: http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/

How to disable RSS feeds on your WordPress blog

Paste the code below into your functions.php file. RSS feeds will not be available anymore after you saved the file.

unction digwp_disable_feed() {
	wp_die(__('<h1>Feed not available, please visit our <a href="'.get_bloginfo('url').'">Home Page</a>!</h1>'));
}
add_action('do_feed',      'digwp_disable_feed', 1);
add_action('do_feed_rdf',  'digwp_disable_feed', 1);
add_action('do_feed_rss',  'digwp_disable_feed', 1);
add_action('do_feed_rss2', 'digwp_disable_feed', 1);
add_action('do_feed_atom', 'digwp_disable_feed', 1);

Thanks to Jeff Starr for the cool tip!

WordPress hack: Automatic “Nofollow” for external links in post content

Paste the following code snippet in your functions.php file. Once you saved the file, all external links in your post content will be changed to nofollow.

add_filter('the_content', 'auto_nofollow');
 
function auto_nofollow($content) {
    //return stripslashes(wp_rel_nofollow($content));
 
    return preg_replace_callback('/<a>]+/', 'auto_nofollow_callback', $content);
}
 
function auto_nofollow_callback($matches) {
    $link = $matches[0];
    $site_link = get_bloginfo('url');
 
    if (strpos($link, 'rel') === false) {
        $link = preg_replace("%(href=S(?!$site_link))%i", 'rel="nofollow" $1', $link);
    } elseif (preg_match("%href=S(?!$site_link)%i", $link)) {
        $link = preg_replace('/rel=S(?!nofollow)S*/i', 'rel="nofollow"', $link);
    }
    return $link;
}

Thanks to One Extra Pixel for the hack!

10+ wp-config tricks to boost your WordPress site

Prevent WordPress from asking FTP credentials

Paste the following line in your wp-config.php file. This file is located in the root of your WordPress install.

define('FS_METHOD', 'direct');

Please note that the code snippet provided above might not work on all hosting providers, and might even cause security issues if your host is badly configured, so avoid using it if you’re not sure about your hosting.

I use VidaHost on CatsWhoCode, WPRecipes and my other blogs. WP Web Host is also good for smaller websites.

Source: http://wp.tutsplus.com/tutorials/security/conquering-the-wp-config-php…

Tell WordPress to remember your FTP credentials

If the above method do not work on your server, or if you don’t want to implement it for some reason, here is another useful snippet. This one simple tells WordPress to remember your FTP credentials so you won’t be asked again when an upgrade is available.

define('FTP_HOST', 'ftp.yoursite.com');
define('FTP_USER', 'Your_FTP_Username');
define('FTP_PASS', 'Your_FTP_password');
define('FTP_SSL', true); // If you can use a SSL connection set this to true

Source: http://admindaily.com/how-to-stop-wordpress-ftp-to-upgrade-plugins.html

Disallow direct file edition

By default, WordPress allows the site administrator to directly edit themes and plugins files through a built-in editor. This is very useful, but if you’re building a site for a client you probably don’t want him to break the site. Here’s a simple way to disallow direct file edition.

define('DISALLOW_FILE_EDIT', TRUE);

Source: http://www.wprecipes.com/how-to-hide-theme-editor…

Automatically empty trash

If you want to define how often the trash should be automatically emptied, here’s the right way to do it:

define('EMPTY_TRASH_DAYS', 1);

Replace 1 by X to empty spam comments automatically every X days. That’s simple as that!

Source: http://www.wprecipes.com/how-to-automatically-empty-trash-on-a-daily-basis

Easily move your WordPress install

WordPress supports an automatic relocation method intended to be a quick assist to getting a site working when relocating a site from one server to another.

To move your WordPress website easily, paste the following line into your wp-config.php file and then follow the steps explained on WordPress Codex.

define('RELOCATE',true); 

Source: http://wp.tutsplus.com/tutorials/security/conquering-the-wp-config-php-file…

Increase WordPress memory limit

By default, WordPress is configured to limit the php memory it uses to 32M. If you receive a message such as “Allowed memory size of xxxxxx bytes exhausted”, you might want to increase this limit, as shown below:

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

Source: http://digwp.com/2010/08/pimp-your-wp-config-php…

Automatic database repair

Added with Version 2.9, there is automatic database optimization support, which you can enable by adding the following define to your wp-config.php file only when the feature is required.

define('WP_ALLOW_REPAIR', true);

Source: http://digwp.com/2010/08/pimp-your-wp-config-php…

WordPress debugging, the easy way

When developing or debugging, it is useful to display errors. But when your site is live, you might not want to show your potential errors to the entire world. Here is simple solution to display errors only when a debug=debug parameter is found on the url.

The first thing to do is to paste the following code into wp-config.php:

if ( isset($_GET['debug']) && $_GET['debug'] == 'debug')
  define('WP_DEBUG', true);

Once done, simply add a GET parameter to the url of the page you’d like to debug, as shown below:

http://www.wprecipes.com/contact?debug=debug

Source: http://yoast.com/wordpress-debug/

Force SSL usage on your wp-admin directory

If you’re running WordPress on a server that supports SSL, you might want to force SSL usage on all admin sessions. To do so, simply define the FORCE_SSL_ADMIN constant in your wp-config.php file, as shown below:

define('FORCE_SSL_ADMIN', true);

Source: http://www.wprecipes.com/how-to-force-using-ssl-on-wp…

Block external requests

Since version 2.8, WordPress allows you to define constants to control access to specific hosts from behind a proxy server.

define('WP_HTTP_BLOCK_EXTERNAL', true);

It will block external requests from that time on. Though, some plugins need external request to work properly. If you experience problems, you can define a whitelist by pasting the code below into wp-config.php. Don’t forget to replace my url by the one needed by the plugin, and note that you should allow access to api.wordpress.org in order to ensure proper functionality of core files and plugins.

define('WP_ACCESSIBLE_HOSTS', 'wprecipes.com');

Source: http://www.wprecipes.com/block-external-requests-on-your-wordpress-blog

Define website url

Introduced in WordPress 2.2, WP_SITEURL and WP_HOME overrides the wp_options table value for home but does not change it permanently, which can be very useful when you move a website to a new domain.

define('WP_HOME', 'http://catswhocode.com'); 
define('WP_SITEURL', 'http://catswhocode.com');  

Source: http://digwp.com/2010/08/pimp-your-wp-config-php…

How to prevent posts from a particular category to be displayed in WordPress loop

Paste the code below into your functions.php file. Don’t forget to update the code with the category ID you want to exclude (on line 4).

// No "Quick Tips" on the homepage
function preventHomepageTips($query) {
  if($query->is_home() && $query->is_main_query()) {
    $query->set('cat', '-40'); // 40 is Quick Tips's category ID
  }
}
add_action('pre_get_posts', 'preventHomepageTips');

Note that David Walsh, the author of this code, have created a plugin which do the same thing as this snippet.

Thanks to David Walsh for the code!

WordPress snippet: Search within a specific post type only

The following code snippet allows you to modify WordPress search engine to search only within a specific post type. Simply update the code with your post type name on line 4, then paste it into your theme functions.php file.

function SearchFilter($query) {
  if ($query->is_search) {
    // Insert the specific post type you want to search
    $query->set('post_type', 'feeds');
  }
  return $query;
}
 
// This filter will jump into the loop and arrange our results before they're returned
add_filter('pre_get_posts','SearchFilter');

Thanks to Hongkiat for the cool code snippet!