Facebook Social Graph WordPress Integration

I love WordPress and have written about them creating WordPress plugins and given away some free ones.

Today I created a plugin that allows you easily integrate WordPress and the Facebook’s open social graph.

ID;
$the_output='';
if(has_post_thumbnail($thePostID))
{
$image_id = get_post_thumbnail_id($thePostID);
$image_url = wp_get_attachment_image_src($image_id);
$the_output.'';
}

$the_output.='';
$the_output.='';
$the_output.='';
$the_output.='';
$the_output.='';
$the_output.='';
echo $the_output;
}
add_action('wp_head', 'facebook_social_meta_init');
}
Advertisement

MySQL via SSH for PHP

I was moving a site from one server to another which has a lot of database transactions, and I did not want to lose any. So at 2am I started the move, at this time the traffic is fairly quiet. Then I realised that neither hosts allowed remote access to MySQL without their super admin’s help. I didn’t like the idea of trying to sync the databases up after the fact so I created an SSH tunnel to the new DB. This meant I could have the old server’s PHP talking to the new server’s MySQL until the DNS propagation was complete.

To do so:

1. I exported a MySQL dump from the old DB server and upload it to the new server

2. In terminal (PuTtY for Windows fans) I SSH into the old server and from there created a port (3377) on the old server which pointed to the new server

[cc lang=”bash”]ssh -L 3377:127.0.0.1:3306 a_user@example.com[/cc]

3. I wanted to see if it worked so I run MySQL in a new terminal window (the existing terminal window needs to remain open, as the switch over of A-Record will not take long I am not worried)

[cc lang=”bash”]mysql -u dbuser -p -h 127.0.0.1 -P 3377[/cc]

4. MySQL on the old server was able to connect to the MySQL instance on the new server

5. Finally I needed PHP on the old server to connect to the MySQL on the new server while the propagation period is taking place

[cc lang=”PHP”]$db = mysqli_connect(‘127.0.0.1’, ‘dbuser’, ‘password’, ‘the_db’, 3377);[/cc]

And that is it!

Using WordPress Functions outside of WordPress

For one of the sites I manage there is something funny happening with the server time. The site uses WordPress and I really like the way WordPress $wpdb class works. In a few sites I manage I occasionally have scripts which preform routine functions which effect the content in WordPress. To use all of the WordPress functions you simply add ‘include_once(“wp-load.php”);’ to the top of you PHP script.

To track the time I created the following script and I have set up a CRON Job to run every minute to track the time on the server.

The PHP is:
[cc lang=”PHP”]include_once(“wp-load.php”);
global $wpdb;
$query=”INSERT INTO time_track (php_time) VALUES (‘”.date(‘Y-m-d H:i:s’).”‘)”;
$wpdb->query($query);[/cc]

By including the wp-load, I have full access to all of the WordPress functions. In this case I am using the $wpdb class which has reduced my code to 3 lines (could be 2 if I typed the query directly into the query function).

The table SQL is:
[cc lang=”SQL”]CREATE TABLE `time_track` (
`id` int(11) NOT NULL auto_increment,
`php_time` timestamp NULL default NULL,
`mysql_time` timestamp NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1[/cc]

This is a great way to have stand alone scripts which interact with the WordPress install. I am sure that the wp-load is adding extra overhead, though it does not matter as only a CRON Job once a minute is calling the script.

Writting a WordPress Plugin

In my post ‘Changing the WordPress Search Form to HTML5‘ I mentioned it could be a made into a plugin. Today we will have a quick look at writing a plugin. We will be building a useless plugin which does basic word filtering, which will change ‘the’ to ‘da’, though not in any smart way. The plugin will be like the ‘egg’ to ‘duck’ word filter from 4Chan’s Moot which resulted in the DuckRoll MeMe.

Getting started:

  • Create a folder into your WordPress Plugins folder e.g. ‘TheToDa’
  • Create a PHP file in the new folder e.g. TheToDa.php
  • Put the key information about your plugin in the top of your file

The header

[cc lang=”PHP”]

/*

Plugin Name: The to Da – Word Filter
Plugin URI: https://createmycomau.files.wordpress.com/2010/12/thetoda.zip
Description: A silly little plugin which will change all the words ‘the’ to ‘da’
Version: 1.0
Author: Dale Hurley
Author URI: http://createmy.com.au
License: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html

Copyright 2010 Dale Hurley (email : dale@createmy.com.au)

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
[/cc]

  • Plugin Name is the name WordPress will show as the name
  • Plugin URI is where the Plugin can be downloaded from
  • Description is a the description used for the plugin which can include some basic HTML
  • Version allows to inform people of the version for upgrades
  • Author and URI creates a link to you
  • License is a URI and the license agreement for the plugin which in this case GPL is being used

Vital, use classes for protection

A lot of plugin tutorials skip over the vital step of wrapping your plugin in a class. By using a class you reduce the chance of code conflict with other plugins. For instance I have seen the function ‘my_admin_init’ used in multiple plugins which will cause WordPress to crash. First we will check that there is no other class with the same name, if there isn’t we will create our class.
[cc lang=”PHP”]if (!class_exists(“the_to_da”))//check that there is no other classes like this
{
class the_to_da //it takes class to use classes
{

}
}//end the check class exists[/cc]

Next we will add our code to create the object using our class.

[cc lang=”PHP”]if (!class_exists(“the_to_da”))//check that there is no other classes like this
{
class the_to_da //it takes class to use classes
{

}
$the_to_da=new the_to_da;//create the new object
}//end the check class exists[/cc]

The functions

Now we will add the function with the same name as the class, this will be executed when the object is called. We will also add our reusable word replace function.

[cc lang=”PHP”]if (!class_exists(“the_to_da”))//check that there is no other classes like this
{
class the_to_da //it takes class to use classes
{
function the_to_da()//construct
{

}

function word_replace($str=”, $from=’the’, $to=’da’)//portable
{

}
}
$the_to_da=new the_to_da;//create the new object
}//end the check class exists[/cc]

The filters

We will add the filters to title, excerpt and content using the add_filter hook. As we are using a class we will use an array to point to the function.

[cc lang=”PHP”] function the_to_da()//construct
{
add_filter(‘the_title’, array(&$this, ‘word_replace’));//add a filter
add_filter(‘the_excerpt’, array(&$this, ‘word_replace’));//add a filter
add_filter(‘the_content’, array(&$this, ‘word_replace’));//add a filter
}[/cc]

Finally we will create our word replace function which is executed any time a title, excerpt or content function is called. This is a dumb word replace, and you would normally use a preg_replace.

[cc lang=”PHP”] function word_replace($str=”, $from=’the’, $to=’da’)//portable
{
return str_replace($from, $to, $str);//replace $from with $to
}[/cc]

Our final code

[cc lang=”PHP”]
/*
Plugin Name: The to Da – Word Filter
Plugin URI: hhttp://createmy.com.au/quick-tip-changing-the-wordpress-search-form-to-html5/
Description: A silly little plugin which will change all the words ‘the’ to ‘da’
Version: 1.0
Author: Dale Hurley
Author URI: http://createmy.com.au
License: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html

Copyright 2010 Dale Hurley (email : dale@createmy.com.au)

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/

if (!class_exists(“the_to_da”))//check that there is no other classes like this
{
class the_to_da //it takes class to use classes
{
function the_to_da()//construct
{
add_filter(‘the_title’, array(&$this, ‘word_replace’));//add a filter
add_filter(‘the_excerpt’, array(&$this, ‘word_replace’));//add a filter
add_filter(‘the_content’, array(&$this, ‘word_replace’));//add a filter
}

function word_replace($str=”, $from=’the’, $to=’da’)//portable
{
return str_replace($from, $to, $str);//replace $from with $to
}
}
$the_to_da=new the_to_da;//create the new object
}//end the check class exists[/cc]

Conclusion

Creating a plugin is really simple. By following some simple practices you will be pumping out plugins daily.

Two final notes is that you should not close you PHP as any white-space after the close will cause WordPress to die. Second, if you are going to publish your plugin you need to include a readme file.

Check out http://codex.wordpress.org/Writing_a_Plugin

Quick Tip – Changing the WordPress Search Form to HTML5 – Free Plugin

It kind of sucks the new WordPress 3’s search form is not HTML 5 when the Twenty10 Theme is. Our new search form will look like the below in Safari.

To make the search form HTML 5, add the following to the functions file of your theme or create a plugin. As a bonus I have turned this into a plugin too. Feel free to download, use, and modify our HTML 5 Search Form plugin. This plugin should be shortly is on the WordPress site.

The below code makes use of the new section element, search input type and placeholder attribute.

[cc lang=”PHP”]function my_search_form( $form ) {
$form = ‘

‘;
return $form;
}

add_filter( ‘get_search_form’, ‘my_search_form’ );[/cc]

To create it as a plugin by adding the following to the top of the PHP.

[cc lang=”PHP”]
/*
Plugin Name: HTML 5 Search Form
Plugin URI: hhttp://createmy.com.au/quick-tip-changing-the-wordpress-search-form-to-html5/
Description: This plugin will change your WordPress search form to a HTML 5 search form.
Version: 1.0
Author: Dale Hurley
Author URI: http://createmy.com.au
License: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*/[/cc]

Remember if you do turn it into a plugin, do NOT close the PHP tag.

HTML 5 – Easier and Better Than XHTML

HTML 4.01 was replaced by XHTML, which 18 months ago I was praising XHTML as the greatest thing. XHTML is a strict version of XML and HTML. XHTML aimed to be a pure XML language and dropped most of the formatting elements like the font, b (bold) and i (italics) tags. XHTML was strict and had the following rules:

  • Elements have to be in lower case
  • Elements’ attributes have to be in lowercase
  • For every element opened, it had to be closed, though you could self-close elements
  • Only the set attributes for each element could be used
  • The document application type needed to be XML, though this was rarely practiced
  • In line elements (e.g. anchor tags for links) were not to wrap around block level (e.g. divs).
  • Double quotation marks had to be used to contain the attributes values
  • Only markup was contained in the document, the presentation and interaction was pushed out to external files

An XHMTL could look like

[cc lang=”XHTML”]

An XHTML Document

Example

This is an example XHTML document.

[/cc]

While the same page in HTML 5 could look like (though is poorly formed):

[cc lang=”html”]

An HTML Document

Example

This is an example HTML document.

[/cc]

Notice in HTML 5:

  • A DOCTYPE is declared, though in XHTML even though it is not required many developers declared it anyway because they do not serve their pages as XML
  • The HTML DTD URI is not declared, useless anyway as browsers ignored the published DTD anyway
  • The body element name is in uppercase, as HTML5 is not case sensitive, though I personally prefer to keep it lower case
  • The class attribute of body is in uppercase (for example purposes only)
  • The value of the class attribute of body is not wrap in quotation marks, in HTML 5 you can use single, double or no quotation marks. Though again I prefer to use double quotation marks for readability.
  • The paragraph attribute is not closed. This actually bugs me as I think it actually makes it easier to find problems and makes it easier to read if the tags are closed.

FYI – HTML/XHTML is a collection of blocks of content, aka elements or tags. These blocks describe the structure of the page. An element is declared by an open angle bracket (), the content, open angle bracket ().

i.e.
[cc][content][/cc]

e.g.
[cc lang=”HTML”]

This is an example paragraph

[/cc]

XHTML by being stricter help developers to form much nicer HTML. It forced you to be discipline and made making updates and debugging a lot easier.

Being unforgiving, XHMTL drove a lot of developers nuts. So I think developers should look at HTML 5’s looser restrictions as a reward and not a right. Documents should be well structured/form, though enjoy the ability to add attributes to tags outside of the spec such as placeholder.

By following the disciplines of XHTML, my HTML 5 example should look like:

[cc lang=”HTML”]

An HTML Document

Example

This is an example HTML document.

[/cc]

This document still looks a lot like the XHMTL document, and not that much easier. This is because we are looking at too simple of a page. A lot of the ease comes in the form of the new elements which help make the HTML more readable and adding functionality.

For example:

  • The video element will eventually replace the need to use Flash or SilverLight to embed videos into the page
  • The placeholder attribute will replace the JavaScript hacks to add placeholders to inputs
  • The new input types will replace the JS hacks for dates, numbers, sliders

HTML 5 The DOCTYPE

In my last post I stated “by introducing the new version of HTML 5 developers will find it much easier to build sites”. So I guess a good place to start with making HTML 5 simpler is to start from the top, which actually is probably the most complicated part of XHTML and HTML.

Most developers working with HTML/XHTML are quite use to the the DOCTYPE declaration at the start of their code. The DOCTYPE tells the browser or other application how to interrupt the mark up language of the page. There is a massive list of the various DOCTYPEs on W3C.

These DOCTYPEs are pretty unforgiving. They are case sensitive and had to be spelt perfectly. The worst part is, most browsers ignored them as they were commonly incorrect.

HTML 5 fixes this problem. Instead of trying to find the DOCTYPE snippet from the last site you built, you now just declare [cc lang=”html”][/cc]. No fluffing around with ridiculous long definitions which you will mess up anyway.

HTML 5 in 5 minutes

HTML 5 is quite a hot topic at the moment, with good reason. HTML 5 is the first major update to HTML in over a decade. In the decade there was XHTML. XHTML was too limiting and very few sites actually were XML documents because they did not render in all browsers. XHTML did teach us a lot of good disciplines which should be followed when developing with HTML 5. When I refer to HTML 5, I am treating it in the broadest sense and including the new JS APIs, CSS3 etc in my descriptions.

The HTML 5 spec is currently being revised by W3C at the moment. It is to replace HTML 4 and XHTML. HTML 5 includes new APIs and features to reflect the modern browsing experience such as:

  • video/audio – without plugins,
  • geolocation – pin point and share your location,
  • web sockets – threaded processing to reduce browser hangs,
  • WebGL – like openGL and DirectX for the browser – game creation,
  • BitMap (canvas)/vector (SVG) image creation -? on the fly graphics,
  • Better page structure elements – Section, Article, Nav element – this is more for developers
  • Backwards compatible and forgiving (XHTML 2 did not want to support this)

HTML 5 is exciting as HTML 4 and XHTML are both too restrictive to developers, too ambiguous to browser vendors and out of date for modern web. Both were hot when a 56kb modem was lightning fast. Today these old standards have become dated which has lead to third party plugins filling the gaps and causing people to get upset (Mr Jobs). By introducing the new version of HTML 5 developers will find it much easier to build sites for the majority of operating systems from mobile phones to mainframes.

At the moment YouTube, Google and FaceBook are experimenting with HTML 5. Google’s search algorithm seems to love the semantic nature of HTML 5.

You can use HTML 5 right now. There is a few things that will need hacks to work in IE. These are not hard to find. If you want a pre built HTML5 / CSS 3 template check out the HTML5 boilerplate which has a lot of IE 6+ fall-backs built into it. Start experimenting with it on new sites going forward.

HTML 5 is the easiest HTML version ever. It cuts out a lot of crap and has been built around the common practices on the web, such as placeholders in text-boxes. It is more forgiving, you can build poorly formed HTML (e.g. not closing your tags), you can create elements, you can use single, double or no quotation marks around attributes’ values (though you probably want to if you ever want to read your HTML). Best part is you do not have to validate (though you should aim to).

Below is a simple HTML 5 page, you actually do not even need the head.

[cc lang=”html”]

Simple HTML 5 page

Checkout the awesome doctype!

[/cc]

Checkout the awesome doctype and how simple this example of a complete HTML page is. Gone is long doctype and HTML version, no one can remember and secretly the browsers ignored, like this one for CreateMy:
[cc lang=”html”]

[/cc]

A full site could look like
[cc lang=”html”]

Simple HTML 5 page

My simple HTML 5 page

Simple DOCTYPES

Checkout the awesome doctype!

Author Dale

[/cc]

While there is a lot of new stuff in the code such as header, footer, nav, section, article and search input type it is a lot easier to read the HTML. You can understand the page structure without too much effort.

In future posts I will cover the new elements above.

FunkAll.com – Lessons from other social media sites

So I have started to rebuild my old site FunkAll.com.

Basically FunkAll is an old social networking site. I originally built it before people understood what social networking was.Back in 2004 people were very skeptical of interacting and sharing your entire life online. Today people are a lot different and in some cases willing to put their credit card details on their profile, a little too far in my opinion.

The big problem we face now is how to find a niche in the social media square. There is dominance by FaceBook, Twitter, and MySpace. Google and Microsoft also want to get in.

So I have started looking at the core of what a social network is:

  • Sharing of information with people,
  • Engaging and interacting with other people,
  • Finding people you know, use to know or would want to know,
  • Making your claim on the the web, and
  • Getting information about people

FaceBook is a clear winner in sharing information with people you know, while Twitter is the leader in spreading information to many. Personally I feel Twitter is like a room full of people yelling and the occasional person responding back or repeating what you yelled. FaceBook is good at sharing lots of crap, especially around social games, I really do not want to help you pick pumpkins.

FaceBook is really good with the ability to tag people in multimedia allowing for greater interaction, especially if you are tagged. FaceBook’s strength for information sharing is the ability to post text, photos, and videos, as well as mark you location, tag, share events, and company pages. If they improved their layout and usability it would be almost impossible to find a niche.

Sharing photos is a strength in the FaceBook and MySpace camps. People like to look at themselves and the people they know. Especially true if you are looking up someone from your past, you want to see if they are hot or not. This needs to be a big part of FunkAll. If you can make uploading and sharing photos really easy then there is opportunity to capture the attention of people. This will defiantly help in network effects. However FaceBook is very good at this already.

Status updates have become a big focus of social media. Twitter is the best at this. The users of Twitter are really focused purely on posting status updates. This due to the fact you can only post text and links, as well as an extremely limited profile. Again FaceBook has a good Wall feature, though it is full of mindless automated messages. LinkedIn, is sort of there, mainly because the content is very focused. I believe status updates are important to allow people to be self-indulgent, not in a bad way. It means they can share with the masses things of interest to them in hope of finding others in their network who are also interested. And in other cases it is just a good way to boost about yourself.

YouTube has made interacting via video and text a form of ongoing dialogue. FaceBook has used in much the same way as photos. There is opportunity to make more with video especially because of the new HTML 5 spec. Though the problem with video is the demand it places on resources. This will be a future focus. Maybe a VC can help here.

Sharing you location and finding others around you is a new way to interact at a whole new level. This is an exciting field that FourSquare has managed? to leverage quite well. Grindr has created a unique social network by allowing gay men to find other gay men around them on their mobiles. Mobile social networking is going to be very big and is very simple to implement. The ability to find people possible at the same conference, concert, airport etc as you is quite exciting. There is also a lot of opportunity in the dating market.

Finding people needs to be easy. At the same time there needs to be a definition around the network people are building:

  • FaceBook – mostly people you know
  • MySpace – mostly people with similar interest
  • Twitter – people you find interesting (too much SPAM)
  • LinkedIn – you professional network

Finding people on these networks is done by:

  • Search
  • Networks/Groups
  • Schools/Organisations
  • Recommendations
  • Friends/Followers of friends
  • Badges on other websites

FunkAll is about being open. Therefore it is more likely to aim to be like the MySpace model of building networks around people, while employing a Twitter type model of followers.

FaceBook has a standard look and feel for every user, Twitter allows you to change you background image and MySpace really lets you make it your own. GeoCities in the 90’s strength was you ability to make something which was totally yours. This was fun. I think this something that FunkAll should aim to do. The MySpace model is really good. The one problem you do face is some profiles can start looking really bad.

Ultimately when people visits these sites they are interested in finding information. The better the data is organised the better. Everything needs to be simple.

If you want please visit my FunkAll.com profile.