Tag Archives: PHP

Programmatically Checking if a WordPress Plugin is Installed

When writing a WordPress plugin, it can sometimes be helpful to tell if another plugin is active or not, whether to prevent conflicts or to extend another plugin that you require as a dependency.

Fortunately, there’s a conditional function built into WordPress for just this task.

if ( is_plugin_active('the-plugin/the-plugin.php') ) {
 //do stuff

The is_plugin_active() function accepts the relative path to the plugin (from the wp-content/plugins directory) as an argument, and returns either TRUE or FALSE.

What Are the Advantages of a PHP Framework?

CodeIgniter. CakePHP. Kohana.

There’s no shortage of PHP frameworks…but why should you use one? What are the major advantages?

  • MVC – The Model-View-Controller architectural pattern helps you tier your code for easier maintenance. By keeping the data-manipulating logic separate from the bits that handle the display, you make it much easier to change either the template or the underlying code without touching the other.
  • Bundled classes – A framework includes classes and helper functions for common tasks, such as database access, pagination, and form handling. Not to mention smaller things, like truncating text to a specific word/character count.
  • Rapid development – Frameworks help you create a small to medium-sized application much quicker than if you wrote everything from scratch. If you’re in a hurry, using a framework will help you finish things before you reach that looming deadline.

If you’re a total DIY type, you don’t even need to rely on a third-party PHP framework. You could assemble on yourself, one that’s more specific to the projects you work on.

Kohana: Cleaner CodeIgniter For PHP 5

KohanaOne of the major criticisms of the CodeIgniter PHP framework is its continued support for PHP 4. The developers of the language announced two years ago that PHP 4 development, security patches included, would cease by the end of 2007. The CodeIgniter project still insists on supporting the outmoded PHP version, because far too many shared hosting providers still haven’t upgraded their machines for fear of breaking peoples’ poorly-coded scripts.

While CodeIgniter’s legacy support doesn’t stop you from using PHP 5-specific features in your applications, it does make things a bit less…elegant. If you’re going to build a sports car, would you put an old, less-efficient engine inside it?

Enter Kohana, “the swift PHP framework.”

Kohana is a fork of CodeIgniter, but entirely rewritten to be strict PHP 5 OOP. There are some different conventions, but overall the frameworks are similar enough that migrating is relatively painless. I’m still reading through the documentation, but it seems like it’s definitely worth looking into. Some of you may prefer CodeIgniter for their larger community, but it you’re a developer who has ever been frustrated by CodeIgniter’s decision, then you definitely want to have a look at Kohana.

PHP stdClass: Storing Data in an Object Instead of an Array

Have you ever seen a scenario where you’re accessing data as an object, such as when you’re using WordPress’s database interface or when you’re parsing XML files with SimpleXML? You have something like echo $result->name.

Have you ever wondered how that was done? Using PHP’s stdClass feature you can create an object, and assign data to it, without having to formally define a class.

Suppose you wanted to quickly create a new object to hold some data about a book. You would do something like this:

$book = new stdClass;
$book->title = "Harry Potter and the Prisoner of Azkaban";
$book->author = "J. K. Rowling";
$book->publisher = "Arthur A. Levine Books";
$book->amazon_link = "http://www.amazon.com/dp/0439136369/";

You can then access the data by calling $book->title and so on.

Continue reading →

Using isset() Instead of strlen() in PHP

I found something interesting in an old Smashing Magazine article. The author describes a slightly faster alternative to the strlen() function in PHP, which is used to determine the length of a string variable.

if (isset($username[5])) {
 // The username is at least six characters long.

An interesting fact about PHP is that a string is technically an array of characters. If the $username string is equal to redwall_hp, you could echo out $username[3] and get w.

The code snippet above uses the isset() language construct to see if the sixth array key, the sixth letter, is set. If it is, then the string must be at least six characters long.

For quick checks during form processing, this might save you a few milliseconds here and there in processing time. It wouldn’t work in situations where you need to know the actual number of characters in a string, as opposed to whether it’s more or less than something.

Regular Expression to Get All Image URLs From a Page

Have you ever wanted to, while working on some sort of PHP project, get an array listing of all the images used in a chunk of HTML? I’ve been planning out a web app over the past couple months, which will be doing a bit of RSS parsing, and I thought it would be nice to do just that, when it came time to start coding. Suppose you were going to show a summary of an article from a feed, with a link to the original source. Wouldn’t it look better if you pulled an image from that article, scaled it down if necessary, and displayed it next to it? (Caching it, of course. Hotlinking == bad.)

I was reading an article from Cats Who Code and, lo and behold, there was a code snippet that did just that with a regular expression. (I decided to file it away to save time in the future.)

$images = array();
preg_match_all('/(img|src)=("|')[^"'>]+/i', $data, $media);
foreach($data as $url)
$info = pathinfo($url);
if (isset($info['extension']))
if (($info['extension'] == 'jpg') ||
($info['extension'] == 'jpeg') ||
($info['extension'] == 'gif') ||
($info['extension'] == 'png'))
array_push($images, $url);

Source: 15 PHP regular expressions for web developers

Feed-parsing is an excellent use for this, as you have just the article, no layout-related imagery, like you would see if you were screen-scraping a web page to obtain the image URLs. Though I imagine Digg takes the latter route when they dig-up (Freudian pun unintended, honest) the thumbnails that go along with their news links.

Get the Average Number of Comments Per Post in WordPress

Comments are often a good metric of how engaged your readers are. The more comments you get per post, the better you are doing as a blogger. If you get a high average of comments per post, then your readers are interesting in your content, they’re reading it through, and they want to discuss the topic more.

Wouldn’t it be a neat trick if you could total up the average number of comments per post on your blog? It’s not too hard. WP Recipes has a little code snippet that does just that.

$count_posts = wp_count_posts();
$posts = $count_posts->publish;

$count_comments = get_comment_count();
$comments  = $count_comments['approved'];

echo 'Average '.round($comments/$posts).' comments per post.';

Automattic WordPress Post Thumbnails

There are plenty of posts floating around the internet about using Custom Fields to assign thumbnail images to individual posts in WordPress. Web Developer Plus has a different idea.

Do you often put images in your posts? You probably upload them through the media manager built right in to the WordPress post editor. Every time you upload an image, it’s associated with the post you first attach it to. And WordPress creates a thumbnail to go along with it, of the size specified in the media settings.

Web Developer Plus has a an article on how to automatically find the thumbnail URL of the first image attached to a post and store it in the variable $img, which you can then echo out into an <img /> tag wherever you want the thumbnail to appear.

Continue reading →

Parse a WordPress Plugin’s README.txt With Regular Expressions

I’ve been working on a neat enhancement for my Tweetable WordPress plugin. Already I have a handy “Documentation” link on the plugin’s pages in the WordPress admin. When clicked, it opens a ThickBox dialog pointing to the README.txt file.

Not bad, but it had a few rough edges. Raw markdown doesn’t look look stellar, and then there was the problem with the horizontal scrollbars that would appear from loading a plain text file into the ThickBox. So I made a new script that would load-up the README.txt file and use Regular Expressions to parse some of the more basic markdown syntax into good old HTML.

README.txt, parsed into HTML

Continue reading →

An Easier Way to Handle Plugin Options in WordPress 2.8

Write forms, collect data from them, validate, then store. That’s the routine familiar to most plugin developers, and one that could always be easier. Why should you have to waste your time writing boring form handling functions when you could be working on one of the more interesting parts of your code?

With WordPress 2.8 comes the register_setting() function, which just might make things a bit easier.

Essentially the function lets WordPress handle the data collection and storage dirty work. After calling register_setting() when the init hook runs, you can just create the form and sanitize the data with a callback function.

add_action('admin_init', 'ozh_sampleoptions_init');
function ozh_sampleoptions_init() {
register_setting('ozh_sampleoptions_options', 'ozh_sample');

Apparently this method works in 2.7 as well, but in 2.8 it is required if you’re using options.php for your settings.