Examples of PHP Code Snippets

So, now you are thinking of installing the PHP Snippet Library plugin, you’re probably wondering what you can use it for. Well, typically, people want to add PHP code to their web site to do one of two things:

  • to change the appearance of their web site, or
  • to change the behavior of their web site.

In most cases, this involves either modify the PHP code of a theme, or taking advantage of the many WordPress action hooks and filters to add new or modified functionality to your site.

In the case of adding PHP code to your theme, you typically have to embed the code directly into the appropriate theme file, and you would not be able to put that in a snippet, although if you put the code in a separate function, you can put that function in a snippet, and you would only need to add the one line of code into the theme file to call that function.

But most of the time, you’re likely to be creating a code snippet that will be called by a WordPress action hook or filter.

Examples

1. Edit Posts Per Page

A very simple snippet that can have a large impact on your administration pages is a one line PHP function to change the number of posts (and pages) that are displayed on the All Posts and  All Pages admin pages.

The default is 20, but you can change this to any number you like. If you want all the posts/pages displayed on the same page, you can make it larger, or if you don’t like to have to scroll down the web page looking for posts, you can make it smaller so that the list fits on your screen.

Here is the snippet code:

function my_edit_posts_per_page($posts_per_page) {
   return 5; // Change this to the number of posts per page you want.
}
add_filter('edit_posts_per_page', 'my_edit_posts_per_page');

Since this snippet is only useful in the admin section of your site, be sure to select “For use in the admin section only.”

2. Current Date Short Code

One of the common reasons for creating PHP snippets is for creating WordPress shortcodes. A shortcode is a user-created tag (in square brackets) that can be embedded anywhere in a post or page to allow the embedding of some kind of generated content. Examples include: the current date or time, or perhaps a smiley face icon, or a hotlink or logo. The variety is endless.

For this example, we’ll stick to something simple — displaying the current date in a post:

function my_current_date($attrs) {
   return date('l jS F Y');
}
add_shortcode('the_date', 'my_current_date');

Once you have created this snippet, you can embed the current date in any post or page just by adding [the_date] into the text.

3. Adding a New Color Setting to the Theme Options page

This snippet requires you to be using the Twenty Eleven theme (the one that currently comes installed with WordPress) and have the Twenty Eleven Theme Extensions plugin installed (which I just happen to be the author of..!). The plugin adds a dozen new color settings for the Twenty Eleven theme, but there are lots more colors in the theme that can be change, if only there were settings for them…

Well, the plugin adds a filter to WordPress that allows you to add more color settings yourself, if you write a small snippet of PHP code that uses it:

/**
 * Custom color settings filter callback. Adds a comment
 * background color setting to Theme Options.
 * @param array $settings array of color settings
 * @return array modified version of the settings array
 */
function my_custom_colors($settings) {
    $settings = array(
        'title' => 'Comment Background Color',
        'styles' => array('background' => '.commentlist > li.comment'),
        'defaults' => array('light' => '#F6F6F6', 'dark' => '#090909')
    );
    return $settings;
}

// Add the custom color settings filter.
add_filter('moz_theme_custom_colors', 'my_custom_colors');

Once this snippet is added, there will immediately be a new theme color option available on the Theme Options page called Comment Background Color, and you can use it to change the comment background color without having to edit the theme’s CSS stylesheet.

4. Snippets as a Development Tool

Here’s an example of a snippet that might help you when developing or debugging a plugin:

function my_check_current_screen() {
    global $current_screen;
    echo "<span style="color: red;"gt;The current screen name is:"
         .$current_screen->id.'</span>';
}
add_action('admin_notices', 'my_check_current_screen');

The code prints out the screen name for the admin settings page you are on, which can be useful if you want to know what screen name to use when your adding help text, for example.

This is the type of snippet you might want to keep around, but only use occasionally, so most of the time you would keep it disabled, and only enable it when you need the information it provides.

Final Words

Those are just four examples of the many types of things you can do with PHP snippets. The best idea is to keep the plugin around while your developing or tweaking your site, and whenever you need to add a bit of PHP code to do something, or come across a useful snippet somewhere on the Internet, consider placing it in the snippet library where you can keep track of it and manage it as you continue to maintain your site.

Just one final note about the function names you use in snippets–be careful not to create generic names that might clash with function names that are already in WordPress or a an installed theme or plugin. A good strategy is to use a unique prefix for all your functions–I tend to use moz_ for mine, for example (so don’t you use it!)–but the safest strategy of all is to wrap all your functions in the following code to test for an existing function with the same name, like this:

if (!function_exists('my_edit_posts_per_page') {
   function my_edit_posts_per_page($posts_per_page) {
      return 5;
   }
}

That still leaves you with a problem of your version of the function never being called, but at least it will stop a PHP error from messing up your web site.

For a small to medium-sized web site, you’re probably safe with a using a prefix (but make sure to use something a little more unique than “my_“), but for large projects, it’s better to be safe than sorry, so use the extra test.

Comments are closed.