Easy WordPress pagination without plugins

Simply paste the following code where you want to display your pagination:

global $wp_query;
$total = $wp_query->max_num_pages;
// only bother with the rest if we have more than 1 page!
if ( $total > 1 )  {
     // get the current page
     if ( !$current_page = get_query_var('paged') )
          $current_page = 1;
     // structure of "format" depends on whether we're using pretty permalinks
     $format = empty( get_option('permalink_structure') ) ? '&page=%#%' : 'page/%#%/';
     echo paginate_links(array(
          'base' => get_pagenum_link(1) . '%_%',
          'format' => $format,
          'current' => $current_page,
          'total' => $total,
          'mid_size' => 4,
          'type' => 'list'
     ));
}

Thanks to Smashing Magazine for the cool tip!

Sending SMS with PHP and TextMagic: An A to Z guide

Step 1: Creating a TextMagic account

In order to send SMS to mobile phones, you need to use a third-party service. In this tutorial, I’m using a service called TextMagic to send SMS. There are lots of other services to do so, but I’ve tested Textmagic and I’m very happy with it so far.

To use TextMagic, you have to create an account. Go here and register. Prices starts at $27 for 200 SMS (13.5 cents per sms)

Step 2: Configure your API account

Once you have created your TextMagic account, go to My services → API → Password. You need to generate an API password in order to be able to send SMS from your website. Just enter your account password and click on “Generate API password”.

Once done, you have to download the API files. Go to this page and click on the “Download” button to get the API files. Extract the textmagic-sms-api-php.zip file and upload all of its content to your server.

Step 3: Let’s code!

Now, we have to create a function that will send the SMS throught the TextMagic API. The following code, taken from TextMagic website is the easiest way to send a SMS using the TextMagic API.

require('textmagic-sms-api-php/TextMagicAPI.php');

$api = new TextMagicAPI(array(
    "username" => "yourTextMeUsername",
    "password" => "yourTextMePassword"
));

$text = "Your message here";

// Use this number for testing purposes. This is absolutely free.
$phones = array(9991234567);

$results = $api->send($text, $phones, true);

So how does this code works? First, I’m including the TextMagic API. Then we have to instantiate a TextMagicAPI object. To do so, you need your TextMagic username as well as your API password. $phones is an array that can contains how many phone numbers as you want. Useful for bulk text messaging!

Finally, the SMS is sent using the sent method. For testing purposes, you can use the 9991234567 number provided by TextMagic. It is totally free!

Now, how to make sure your SMS has been sent? Easy, just see if $results is true:

if ($results = $api->send($text, $phones, true)){
    echo "SMS sent successfully!";
}

You’re done. This is basically all you need to send text messages with TextMagic.
By the way, if anyone ever heard of a free and reliable service to send SMS, please let me know in a comment!

10+ useful SQL queries to clean up your WordPress database

Two things to note: First, any of these queries should be preceded by a backup of your whole database. Secondly, don’t forget to replace the wp_ table prefix by the prefix used on your WordPress install, otherwise the queries won’t work.

Clean up your WordPress database from weird characters

Encoding problems can be really painful. Instead of manually update all of your posts, here is a query that you can run in order to clean your database from weird characters.

UPDATE wp_posts SET post_content = REPLACE(post_content, '“', '“');
UPDATE wp_posts SET post_content = REPLACE(post_content, '”', '”');
UPDATE wp_posts SET post_content = REPLACE(post_content, '’', '’');
UPDATE wp_posts SET post_content = REPLACE(post_content, '‘', '‘');
UPDATE wp_posts SET post_content = REPLACE(post_content, '—', '–');
UPDATE wp_posts SET post_content = REPLACE(post_content, '–', '—');
UPDATE wp_posts SET post_content = REPLACE(post_content, '•', '-');
UPDATE wp_posts SET post_content = REPLACE(post_content, '…', '…');

UPDATE wp_comments SET comment_content = REPLACE(comment_content, '“', '“');
UPDATE wp_comments SET comment_content = REPLACE(comment_content, '”', '”');
UPDATE wp_comments SET comment_content = REPLACE(comment_content, '’', '’');
UPDATE wp_comments SET comment_content = REPLACE(comment_content, '‘', '‘');
UPDATE wp_comments SET comment_content = REPLACE(comment_content, '—', '–');
UPDATE wp_comments SET comment_content = REPLACE(comment_content, '–', '—');
UPDATE wp_comments SET comment_content = REPLACE(comment_content, '•', '-');
UPDATE wp_comments SET comment_content = REPLACE(comment_content, '…', '…');

→ Source: http://digwp.com/2011/07/clean-up-weird-characters-in-database

Close trackbacks on all posts at once

Do you use trackbacks and pings? Many people seems to find them useless. In order to get rid of them, you can close trackbacks post by post, but this will consume a lot of time. Or, of course, you can use a good old SQL query, as shown below:

UPDATE wp_posts SET ping_status = 'closed';

→ Source: http://www.wprecipes.com/wordpress-tip-close-trackbacks-on-all-posts-at-once

Get rid of all unused shortcodes

I love WordPress shortcodes, but there’s a problem with them: Once you stop using a shortcode (for example when you switch to another theme) you’ll find shortcodes in full text on your posts. Here’s a SQL query to remove them. Just update the code with the shortcode you want to remove. I’ve used [tweet] in this example.

UPDATE wp_post SET post_content = replace(post_content, '[tweet]', '' ) ;

→ Source: http://www.wprecipes.com/wordpress-tip-get-rid-of-unused-shortcodes

Delete specific post meta

If you used to add a specific custom field to your posts but do not need it anymore, you can remove the undesired meta quickly with this query.

DELETE FROM wp_postmeta WHERE meta_key = 'YourMetaKey';

→ Source: http://www.esoftload.info/10-sql-statements-for-wordpress

Delete all unused post tags

Remember 4 or 5 years ago, tags where very popular in blogging. But now, many bloggers stopped used them. If you did, save some space on your database by cleaning it from unused tags.

DELETE FROM wp_terms WHERE term_id IN (SELECT term_id FROM wp_term_taxonomy WHERE count = 0 );
DELETE FROM wp_term_taxonomy WHERE term_id not IN (SELECT term_id FROM wp_terms);
DELETE FROM wp_term_relationships WHERE term_taxonomy_id not IN (SELECT term_taxonomy_id FROM wp_term_taxonomy);

→ Source: http://4rapiddev.com/tips-and-tricks/wordpress-delete…

Delete feed cache

WordPress stores the feed cache in the wp_options table. If you want to flush the feed cache, you can do so by using the following query:

DELETE FROM `wp_options` WHERE `option_name` LIKE ('_transient%_feed_%')

→ Source: http://wpengineer.com/2114/delete-all-feed-cache…

Delete all post revisions and their metadata

Post revisions is an useful feature, but if you don’t delete the many revisions from time to time your database will quickly become very big. The following query deletes all post revisions as well as all the metadata associated with the revisions.

DELETE a,b,c FROM wp_posts a WHERE a.post_type = 'revision' LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id) LEFT JOIN wp_postmeta c ON (a.ID = c.post_id);

→ Source: http://www.onextrapixel.com/2010/01/30/13-useful-wordpress-sql-queries…

Batch delete old posts

Don’t need those posts published years ago? Delete them using this query. This example is set to delete any post which is older than 600 days. If you want to make an even better version of this query, what about mixing it with the one below to remove old posts as well as their metadata?

DELETE FROM `wp_posts`
WHERE `post_type` = 'post'
AND DATEDIFF(NOW(), `post_date`) > 600

→ Source: http://stackoverflow.com/questions/5317599/wordpress-automatically-delete-posts…

Remove comment agent

By default, when someone comments on your blog, WordPress saves the user agent in the database. It can be useful for stats, but for 95% of bloggers it is just useless. This query will replace the user agent with a blank string, which can reduce your database size if you have lots of comments.

update wp_comments set comment_agent ='' ;

→ Source: http://www.rsatechnologies.in/best-sql-queries-for…

Batch disable all plugins

Sometimes, for exemple when you have to upgrade your blog, you need to disable all your plugins. Depending to how much plugins you’re using, it can takes a lot of time and be kinda boring. Here is an useful SQL query to disable all your plugins at once!

UPDATE wp_options SET option_value = '' WHERE option_name = 'active_plugins';

→ Source: http://www.wprecipes.com/how-to-disable-all-your-plugins…

Change author attribution on all posts at once

Do you need to change author attribution on many posts? If yes, you don’t have to do it manually. Here’s a handy query to do the job for you.

The first thing to do is getting the IDs of WordPress users. Once logged in phpmyadmin, insert the following SQL command:

SELECT ID, display_name FROM wp_users;

Right now, phpmyadmin displayed a list of WordPress users associated with their IDs. Let’s say that NEW_AUTHOR_ID is the ID of the “new” author, and OLD_AUTHOR_ID is the old author ID.

UPDATE wp_posts SET post_author=NEW_AUTHOR_ID WHERE post_author=OLD_AUTHOR_ID;

That’s all. Once this last command has been run, all posts from the old author now appears to have been written by the new author.
→ Source: http://www.wprecipes.com/how-to-change-author-attribution…

WordPress tip: Replace excerpt ellipsis with post permalink

Paste the following code into your functions.php file. Once saved, the tip will be applied to your blog.

function replace_excerpt($content) {
       return str_replace('[...]',
               '... <div class="more-link"><a href="'. get_permalink() .'">Continue Reading</a></div>',
               $content
       );
}
add_filter('the_excerpt', 'replace_excerpt');

Thanks to CSS Tricks for the great snippet!

10 awesome HTML5 audio players

Media Element


MediaElement is an audio an video player which is written in pure HTML5 and CSS. Older browsers are supported by Custom Flash and Silverlight players that mimic the HTML5 MediaElement API.
Media Element is skinnable, and offers plugins for popular platforms such as WordPress, Drupal, Joomla, etc.

→ Visit http://mediaelementjs.com/

Scott Andrew’s HTML5 audio player


This player is very minimalist but works well. Great to use when you do not need playlists or any fancy effects!

→ Visit http://www.scottandrew.com/pub/html5audioplayer/

Speakker


Here is a great player, probably my favorite from the whole list. Speakker is super easy to set up and comes out of the box in two variations and with incredible options of customization: Flexible dimensions, unlimited colors, etc…
Speakker is cross-browser compatible and have a Flash fallback for old browsers.
and two different button sets for light and dark themes.

→ Visit http://www.speakker.com/

MooTools HTML5 Audio Player


Are you using Mootools on your website? If yes, you’ll probably enjoy this player, made with HTML5 and the Mootools JavaScript framework. The player works perfectly on all recent browsers.

→ Visit http://simulacre.org/mootools-html5-audio-player/

Universal HTML5 Audio Player


This player is the only one from the list which isn’t free. But it’s cheap ($5 only!) and works well. It have lots of useful features, such as a way to protect your audio from being hijacked by using a beep overlay, which is a great solution for commercial uses.

→ Visit http://codecanyon.net/item/universal-html5-audio-player

SoundManager 2


Using HTML5 and Flash, SoundManager 2 provides reliable cross-platform audio under a single lightweight (10 kb) JavaScript API.
Want to see what you can do with Sound Manager 2? Then visit http://wheelsofsteel.net/ for an awesome demo!

→ Visit http://www.schillmania.com/projects/soundmanager2/

jplayer


jplayer is a jQuery plugin which have been my audio player of choice for several months because of its simplicity. A great tool which can also play videos.

→ Visit http://jplayer.org/

audio.js


audio.js is a drop-in javascript library that allows HTML5′s <audio> tag to be used anywhere. It uses native <audio> where available and an invisible flash player to emulate <audio> for other browsers. It provides a consistent html player UI to all browsers which can be styled used standard css.

→ Visit http://kolber.github.com/audiojs/

HTML5 Audio Player Bookmarklet


This bookmarklet adds an audio player to play linked audio files on any page. It can be used on any page which has links to downloadable audio files. A great tool to stream audio instead of downloading!

→ Visit http://marklets.com/HTML5+Audio+Player.aspx

WordPress tip: Add extra contact methods to user profiles

Nothing complicated: Just paste the following code into your function.php file. Edit lines 4 and 5 according to your needs.

add_filter('user_contactmethods', 'my_user_contactmethods');

function my_user_contactmethods($user_contactmethods){
  $user_contactmethods['twitter'] = 'Twitter Username';
  $user_contactmethods['facebook'] = 'Facebook Username';

  return $user_contactmethods;
}

Hungry for code snippets? I just opened a snippet library on CatsWhoCode, which include lots of WordPress snippets. Have a look, and don’t hesitate to submit yours!

Thanks to TutsPlus for the cool tip!

WPRecipes contest: win 3 Mighty Deals!

A word about Mighty Deals

Mighty Deals offers unbelievable deals and discounts for creative professionals.The deals include products and services that are heavily discounted, exclusively for Mighty Deals customers, usually from 50% to 90% off. Each deal stays on the site for a very limited time and is available exclusively for purchase directly through the site.

For example, this week deals includes 1000 royalty free vector icons for only $25!

How to join the contest?

Taking part in the contest is super easy: Just enter your email below to subscribe to Mighty Deals. Once done, simply leave a comment on this post to let us know what deal you want. 3 winners will be choosen using random.org, and they’ll recive the deal of their choice.

Winners will be announced in one week, on tuesday 21, 2012. Good luck everyone!

Introducing CatsWhoCode code snippet library!

A code snippet library on CWC?

Over the years, CatsWhoCode has become a place of interest for web developers. Most popular articles on the blog are those who showcase useful code snippets which can be used directly on your projects.

This is why I decided to go further in that direction, and create a place where people can easily find useful code snippets. I have added some snippets but for now the whole library looks a bit empty. Don’t worry, I add snippets everyday so it will not take very long until we have a consistent collection of code snippets!

Visit CatsWhoCode.com code snippets library!

Submit your own snippets

CWC code library allows developers to submit their own code snippets so they can share them with other developers. When submitting a code snippet, you are able to link to your own website so you’ll get (hopefully) a few visits to your website. The link is dofollow, so submitting quality snippets is also good for your SEO.

All submission will be manually approved or declined, to ensure the quality of the library. I rather focus on quality than quantity. Want to submit a cool code snippet? Go here!

How to display your latest tweets on your WordPress blog without any plugin

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>

Thanks to Smashing Magazine for this great code!

Amazing things to do with PHP and cURL

Check if a specific website is available

Want to know if a specific website is available? cURL is here to help. This script can be used with a cron job to monitor your websites.

Don’t forget to update the script with the url you want to check on line 3. Once done, just paste it somewhere and it will let you know about the site availability.

<?php

       if (isDomainAvailible('http://www.css-tricks.com'))
       {
               echo "Up and running!";
       }
       else
       {
               echo "Woops, nothing found there.";
       }

       //returns true, if domain is availible, false if not
       function isDomainAvailible($domain)
       {
               //check, if a valid url is provided
               if(!filter_var($domain, FILTER_VALIDATE_URL))
               {
                       return false;
               }

               //initialize curl
               $curlInit = curl_init($domain);
               curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
               curl_setopt($curlInit,CURLOPT_HEADER,true);
               curl_setopt($curlInit,CURLOPT_NOBODY,true);
               curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);

               //get answer
               $response = curl_exec($curlInit);

               curl_close($curlInit);

               if ($response) return true;

               return false;
       }
?>

→ Source: http://css-tricks.com/snippets/php/check-if-website-is-available/

cURL replacement for file_get_contents()

The file_get_contents() function is very useful but it is unfortunely deactivated by default on some webhosts. Using cURL, we can write a replacement function that works exactly like file_get_contents().

function file_get_contents_curl($url) {
	$ch = curl_init();

	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
	curl_setopt($ch, CURLOPT_URL, $url);

	$data = curl_exec($ch);
	curl_close($ch);

	return $data;
}

→ Source: http://snipplr.com/view/4084

Get latest Twitter status

Using PHP and cURL, it is pretty easy to get the status of a specific user. Once you have it, what about displaying it on your blog, like I do in WPRecipes footer?

function get_status($twitter_id, $hyperlinks = true) {
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/$twitter_id.xml?count=1");
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    $src = curl_exec($c);
    curl_close($c);
    preg_match('/<text>(.*)<\/text>/', $src, $m);
    $status = htmlentities($m[1]);
    if( $hyperlinks ) $status = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", '<a href="%5C%22%5C%5C0%5C%22">\</a>', $status);
    return($status);
}

The function is super easy to use:

echo get_status('catswhocode');

→ Source: http://www.catswhocode.com/blog/php-snippets-to-interact-with-twitter

Twitter: test friendship between two users

If you want to know if a specific user is following you (or someone else) you have to use the Twitter API. This snippet will echo true if the two users specified on lines 18 and 19 are friends. It will return false otherwise.

function make_request($url) {
	$ch = curl_init();
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	$result = curl_exec($ch);
	curl_close($ch);
	return $result;
}

/* gets the match */
function get_match($regex,$content) {
	preg_match($regex,$content,$matches);
	return $matches[1];
}

/* persons to test */
$person1 = 'phpsnippets';
$person2 = 'catswhocode';

/* send request to twitter */
$url = 'https://api.twitter.com/1/friendships/exist';
$format = 'xml';

/* check */
$persons12 = make_request($url.'.'.$format.'?user_a='.$person1.'&user_b='.$person2);
$result = get_match('/<friends>(.*)<\/friends>/isU',$persons12);
echo $result; // returns "true" or "false"

→ Source: http://www.catswhocode.com/blog/php-snippets-to-interact-with-twitter

Download and save images from a page using cURL

Here is a set of functions that can be very useful: Give this script the url of a webpage, and it will save all images from this page on your server.

function getImages($html) {
    $matches = array();
    $regex = '~http://somedomain.com/images/(.*?)\.jpg~i';
    preg_match_all($regex, $html, $matches);
    foreach ($matches[1] as $img) {
        saveImg($img);
    }
}

function saveImg($name) {
    $url = 'http://somedomain.com/images/'.$name.'.jpg';
    $data = get_data($url);
    file_put_contents('photos/'.$name.'.jpg', $data);
}

$i = 1;
$l = 101;

while ($i < $l) {
    $html = get_data('http://somedomain.com/id/'.$i.'/');
    getImages($html);
    $i += 1;
}

→ Source: http://stackoverflow.com/questions/7747875/grab-download-images-from-multiple-pages-using-php-preg-match-all-curl

Convert currencies using cURl and Google

Converting currencies isn’t very hard to do, but as the currencies fluctuates all the time, we definitely need to use a service like Google to get the most recent values. The currency() function take 3 parameters: from, to, and sum.

function currency($from_Currency,$to_Currency,$amount) {
    $amount = urlencode($amount);
    $from_Currency = urlencode($from_Currency);
    $to_Currency = urlencode($to_Currency);
    $url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";
    $ch = curl_init();
    $timeout = 0;
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $rawdata = curl_exec($ch);
    curl_close($ch);
    $data = explode('"', $rawdata);
    $data = explode(' ', $data['3']);
    $var = $data['0'];
    return round($var,2);
}

→ Source: http://l33ts.org/forum/Thread-PHP-Convert-currencies-using-Google-and-cURL-Snippet

Get remote filesize using cURL

Want to be able to calculate the size of a specific file? The following function can help. It takes 3 parameters: the file url, and in case the file is password protected, a username and a password.

function remote_filesize($url, $user = "", $pw = ""){
    ob_start();
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);

    if(!empty($user) && !empty($pw))
    {
        $headers = array('Authorization: Basic ' .  base64_encode("$user:$pw"));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }

    $ok = curl_exec($ch);
    curl_close($ch);
    $head = ob_get_contents();
    ob_end_clean();

    $regex = '/Content-Length:\s([0-9].+?)\s/';
    $count = preg_match($regex, $head, $matches);

    return isset($matches[1]) ? $matches[1] : "unknown";
}

→ Source: http://megasnippets.com/source-codes/php/get_remote_filesize

FTP upload with cURL

PHP does have a FTP library, but you can also use cURL to upload files on a FTP server. Here is a working example:

// open a file pointer
$file = fopen("/path/to/file", "r");

// the url contains most of the info needed
$url = "ftp://username:[email protected]:21/path/to/new/file";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// upload related options
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize("/path/to/file"));

// set for ASCII mode (e.g. text files)
curl_setopt($ch, CURLOPT_FTPASCII, 1);

$output = curl_exec($ch);
curl_close($ch);

→ Source: http://net.tutsplus.com/tutorials/php/techniques-and-resources-for-mastering-curl/