Browsed by
Category: Open Source

How to: Automatically add a default set of Custom Fields to each post in WordPress

How to: Automatically add a default set of Custom Fields to each post in WordPress

PrincipiaPilot.org screenshot showing Custom Fields being used in a template

One of the neat things about WordPress is how easy it is to add custom metadata to a given page or post that you can then use in a template to display structured information. I’ve been using this technique for a while now to extend the basic WordPress elements of title, body, excerpt, etc and allow the creation of easily editable information-rich content.

Before now I’ve used the built-in WordPress Custom Field functionality in the Add New screen where you select previously created custom fields from a drop-down list that is limited to only showing 30 items. This is quite cumbersome as you have select each field you want to add to the entry and enter the value, click the Add Custom Field button, then repeat for however many custom fields you want to use. Needless to say, this can be frustrating to have to remember to do every time, especially for non-technical clients.

The Old Way:

Selecting a Custom Field (the old way)

During a recent site conversion to WordPress that involves 4-6 custom fields for each post, we finally decided that there must be a better way, and ended up finding a WordPress plugin that is so good that it should probably be added to WordPress core, it is so highly useful. The plugin is called Custom Field Template and is developed by Hiroaki Miyashita.

The New Way:

Custom Field Template WordPress plugin screenshot

Using a simple set of options to define the template you want to use is easy. After downloading and activating the plugin, go to Settings > Custom Field Template to define your template. One is provided for you to show you the possible template values. You can set up two separate custom field template designs.

This is the code used to generate the Custom Field Template form shown in the screenshot above:

Template Instruction

<strong>Story Template Metadata Instructions <em>(All fields are optional)</em></strong><br /><br />
1. Use this form to enter metadata about this story.<br />
2. Each item will get assigned to the correct Custom Field for use in the display template.<br />
3. Click the <strong>Save</strong> button to save the values.<br />
<br />

Template Content

[summary_deck]
type = textarea
rows = 3
cols = 50
label = Summary Deck:

[byline_writer_name]
type = text
size = 35
label = Byline Writer Name:

[byline_writer_title]
type = text
size = 35
label = Byline Writer Title:

[byline_writer_picture_url]
type = text
size = 54
label = Byline Writer Picture URL:

[lead_photo_caption]
type = textarea
rows = 3
cols = 50
label = Lead Photo Caption:

[lead_photo_credit]
type = text
size = 35
label = Lead Photo Credit:

[lead_photo_url]
type = text
size = 54
label = Lead Photo URL:

Then set this setting to true by checking the box to make the form look prettier:
Custom Field Template WordPress plugin setting

Next, I tweaked the Admin CSS settings to right-justify the labels:

#cft dl { clear:both; margin:0; padding:0; width:100%; }
#cft dt { float:left; font-weight:bold; margin:0; padding: 0 8px 0 0; text-align:right; width: 20%; }
#cft dt .hideKey { visibility:hidden; }
#cft dd { float:left; margin:0; text-align:left; width:70%; }
#cft dd p.label { font-weight:bold; margin:0; }
#cft_instruction { margin:10px; }

Click Update Options to save the settings and then go to Posts > Add New to see the form in action. You may need to go back and forth a couple of times to get your text field sizes just right and to put them in the right order you want them in.

Using the Custom Fields in a template

So how do these values get displayed on your page?

Simply edit your template PHP file to look for custom field values and then display them where you want them if they’re present.

This is how I do it for the Principia Pilot site. This code goes at the top of the template for single.php

<?php
// Retrieve custom meta values from post if they're present
$byline_writer_name = htmlspecialchars(get_post_meta($post->ID, "byline_writer_name", true));
$byline_writer_title = htmlspecialchars(get_post_meta($post->ID, "byline_writer_title", true));
$byline_writer_picture_url = htmlspecialchars(get_post_meta($post->ID, "byline_writer_picture_url", true));
$lead_photo_url = htmlspecialchars(get_post_meta($post->ID, "lead_photo_url", true));
$lead_photo_credit = htmlspecialchars(get_post_meta($post->ID, "lead_photo_credit", true));
$lead_photo_caption = htmlspecialchars(get_post_meta($post->ID, "lead_photo_caption", true));
$summary_deck = wptexturize(get_post_meta($post->ID, "summary_deck", true));
?>

Now each of the possible Custom Fields are available as PHP variables that can be checked for content.

This code example shows the “summary deck” being displayed on the page if it has been entered on the create content screen:

<?php
// Show summary deck if we have one
if ($summary_deck != "") {
    echo '<h3 class="summary-deck">' . $summary_deck . '</h3>';
}
?>

Using this excellent plugin, you can set up select lists, radio buttons, check boxes and more to help you populate your Custom Fields more easily if you prefer that to using simple text fields. You can also specify default values to use for the custom fields so you don’t have to type them in every time.

Plugin Default Template Options

These are the default options included by the plugin:
[Plan]
type = text
size = 35
label = Where are you going to go?

[Plan]
type = textfield
size = 35
hideKey = true

[Favorite Fruits]
type = checkbox
value = apple # orange # banana # grape
default = orange # grape

[Miles Walked]
type = radio
value = 0-9 # 10-19 # 20+
default = 10-19
clearButton = true

[Temper Level]
type = select
value = High # Medium # Low
default = Low

[Hidden Thought]
type = textarea
rows = 4
cols = 40
tinyMCE = true
mediaButton = true

Which displays a form that looks like this:
Custom Field Template WordPress plugin screenshot - Default form options

Summary

This plugin addresses a key need when using Custom Meta Fields in a WordPress custom template design — making it as easy as possible to enter values time after time on multiple pages or posts. There are a bunch of other neat options this plugin offers to make the authoring experience even easier. This is now on my “must install” list of essential WordPress plugins.

Please support Open Source by donating to the plugin author

If you use this and like it, I highly recommend sending a nice donation to the plugin author to help support ongoing development and to say thanks. This plugin will save you and your clients a lot of time and frustration. Thanks Hiroaki!


Requirements

Requires WordPress 2.1 or higher.

Click here to download Custom Field Template plugin from WordPress.org

Why you should upgrade your WordPress installation to version 2.6 (just released) today

Why you should upgrade your WordPress installation to version 2.6 (just released) today

WordPress 2.6 is Available! Security Advisory to upgrade ASAP!

First, the good news: Matt & his brave crew of WordPress coders have just released version 2.6 of the Open Source award-winningly awesome content management system called WordPress (download it here). I’ve been using it since it was called b2, and love it. I recommend it for most of my clients, and they love the simplicity and ease of use. I also really like how easy it is to customize and extend, using the excellent theme and plugin system.

If you have a WordPress installation yourself, please upgrade it today. Why should you do it today? In short, not only does the latest version of WordPress have some awesome new features (like content change tracking, a new “Press this” browser bookmark, using Google’s Gears system to make it faster, and about 194 bug fixes) it also contains the latest SECURITY FIXES.

Why should you care about security fixes? Because older versions of WordPress are vulnerable to exploits. I know this for a fact, and have been working on cleaning out a number of older installations of WordPress that have been hacked. This isn’t a fun process, and if you stay up to date, you will have the best chance of not getting hacked yourself.

This isn’t a problem exclusive to WordPress, and they’ve done a really good job generally at fixing holes (the current release proactively fixes a number of potential issues), but it is an issue you should definitely look into.

On a Unix machine, one thing to look for is this pattern in any files: md5($_COOKIE'

You can do a search through all your hosting accounts by running this command (run as root):
# grep -R 'md5($_COOKIE' /home/

That will tell you if you have any infected files (for this particular exploit). If you find any, you need to clean out those files. If you are running your sites out of version control (like using svn), this may be slightly easier.

$ svn st should tell you if any files were changed from the last time you checked them out. If you see unexpected files show up, you’ve been hacked.

To clean out your installation, not using version control method (done as root in this case):

  1. Copy your whole public_html directory to another location so you can do forensics on it and copy valid files back into your new installation:
    # cd /home/USERNAME/
    # mkdir public_html-hacked
    # mv public_html/* public_html-hacked/
  2. Download a clean copy of WordPress into your public_html:
    # cd /home/USERNAME/
    # wget http://wordpress.org/latest.zip .
    # unzip latest.zip
    # cp -R wordpress/* public_html/
    # chown -R USERNAME:USERNAME public_html/*
  3. Create a new wp-config.php file. It’s probably a really good idea to first change your MySQL database password. To create your new config file:
    #cd public_html/
    # cp wp-config-sample.php wp-config.php
    # vi wp-config.php

    Enter the correct (new) values for your MySQL database name, username, password, and the (currently 3) authorization unique key values (go to http://api.wordpress.org/secret-key/1.1/ to automatically generate the 3 keys for you to copy/paste into your config file.
  4. Next, upgrade your WordPress database: http://example.com/wp-admin/upgrade.php. You’ll have to sign in with your admin username and password. Once this is done (should go without a hitch, hopefully), examine your user table to see if there are any entries there that shouldn’t be. Delete any users that you didn’t create. Also, it would be a good idea to update the password for each user in the system.
  5. Go through all of your Settings, looking for any suspicious changes. Specifically notice what the Uploads directory is set to (in Settings->Miscellaneous). It should probably be set to something like wp-content/uploads. If it says something like ../../../../../tmp/ change it back. Also go look there to see if there are any left-over files that need to be investigated and removed.
  6. Make a local copy backup of your database and then clean out entries that don’t belong there. Check your raw database (using something like PHPMyAdmin or command line mysql tools) and examine the wp_users table. Look for a user called WordPress. Delete it! If you found it, also check the wp_usermeta table and delete all entries associated with the bogus WordPress user ID. Next, check through your other MySQL tables to look for any suspicious entries (attached files, comments, posts, etc.) Delete anything that looks incorrect or wrong, but be sure not to delete your actual content.

As you can see, there are lots of things to check for if your installation of WordPress gets compromised. So, to save yourself a lot of pain and suffering, make sure you upgrade your WordPress installation(s) just as soon as you can.

More good info if you think your WordPress installation has been hacked:

How to connect to a VNC machine that is behind a firewall using SSH tunneling, OS X and Chicken of the VNC

How to connect to a VNC machine that is behind a firewall using SSH tunneling, OS X and Chicken of the VNC

VNC is a very useful program for accessing a computer remotely. These are instructions for accessing a remote machine using OS X, Chicken of the VNC, and Vine Server when there is a firewall in the way.

VNC SSH Tunnel

Normally it is a fairly straightforward process to connect from a VNC client to a VNC server running on a remote machine. A firewall in the middle can complicate the process a bit.

Normal:
MY MACHINE -> VNC CLIENT < - -> VNC SERVER < - REMOTE MACHINE Behind firewall: REMOTE MACHINE -> VNC SERVER -> SSH TUNNEL < - -> VNC CLIENT < - MY MACHINE

  1. On MY MACHINE, create a local SSH user account and password – call it vnc_user
  2. On MY MACHINE, determine my public IP address – go to whatismyip.com (MY_IP_ADDRESS)
  3. On REMOTE MACHINE, turn on the Vine Server and set the password
  4. On REMOTE MACHINE, open up Terminal and enter the following command:

    ssh vnc_user@MY_IP_ADDRESS -R 5900:127.0.0.1:5900

    where MY_IP_ADDRESS is the IP address of MY MACHINE.

  5. Enter the password for the vnc_user. You should now be connected to MY MACHINE over SSH.
  6. On MY MACHINE, open up Chicken of the VNC. Connect to localhost and enter the password for the REMOTE MACHINE.
  7. You should now be connected to REMOTE MACHINE’s VNC server and be seeing their screen.
  8. Notes:

    • Make sure that you are not running a VNC server on MY MACHINE, or that it is turned off
    • If you are running a firewall on your own network, you may need to enable port forwarding for SSH to ensure that SSH requests on port 22 are connected to MY MACHINE and not blocked by your own firewall.

    Thanks to this article that describes how to do this and also includes an Applescript that makes the connection.

New site design is live (also upgraded to the latest version of WordPress – 2.5)

New site design is live (also upgraded to the latest version of WordPress – 2.5)

New site design is finally live!

In preparation for upgrading a whole mess of sites to using the latest version of WordPress I decided it was time to finally upgrade my own site and to implement the new design I’d been working on for a while (for over a year now).

Check it out: www.gabrielserafini.com

How to fix PEAR installation of XML_RSS / XML_Tree invalid package.xml file problem

How to fix PEAR installation of XML_RSS / XML_Tree invalid package.xml file problem

As part of getting an upgraded server set up and transferring sites from the older server, I had to re-install PEAR XML_RSS. One of its dependencies is XML_Tree.

Normally, this command should have worked with no problems:

pear install XML_RSS

It downloaded XML_RSS just fine, but then choked on XML_Tree, which was a required dependency.

Initial output:

# pear install XML_RSS
Did not download dependencies: pear/XML_Tree, use --alldeps or --onlyreqdeps to download automatically
pear/XML_RSS requires package "pear/XML_Tree"
No valid packages found
install failed

My next try was to specify installing XML_Tree:

# pear install XML_Tree
WARNING: "pear/XML_Tree" is deprecated in favor of "pear/XML_Serializer"
downloading XML_Tree-1.1.tgz ...
Starting to download XML_Tree-1.1.tgz (4,826 bytes)
.....done: 4,826 bytes
XML error: not well-formed (invalid token) at line 10
Download of "pear/XML_Tree" succeeded, but it is not a valid package archive
Error: cannot download "pear/XML_Tree"
Download failed
install failed

After some troubleshooting, here is how I fixed this problem:

  1. Change directory into the PEAR download cache directory: cd /tmp/pear/cache/
  2. Clear out all the old cache files: pear clear-cache
  3. You should see the downloaded file: XML_Tree-1.1.tgz
  4. Extract the files: tar xvfz XML_Tree-1.1.tgz
  5. Now edit the extracted package.xml file: vi package.xml
  6. Go to line 10 and change the ö to an o. This is the character that is causing the XML validation of the package file to fail. Next, save the file (ESC :wq)
  7. Next, remove the old .tgz file: rm -rf XML_Tree-1.1.tgz
  8. We’re going to recreate the package: tar cfv - package.xml XML_Tree-1.1/ | gzip > XML_Tree-1.1.tgz
  9. Next, we’re going to install this package and not use the network: pear install -O XML_Tree-1.1.tgz

XML_Tree is now installed. You should now be able to continue installing XML_RSS normally.

How to sync audio and video for DVD playback using your remote speakers, AirPort Express, Rogue Amoeba’s Airfoil and VLC

How to sync audio and video for DVD playback using your remote speakers, AirPort Express, Rogue Amoeba’s Airfoil and VLC

Apple AirPort Express

I’ve been enjoying using my Apple AirPort Express to stream music from my laptop to our living room speakers using iTunes. The other evening I wanted to watch a DVD and use the good speakers to get the best sound, but you can’t do that without using a helper program.

Rogue Amoeba's Airfoil

I found a program that lets you route any audio signals to your AirPort Express — it’s called Airfoil (free to try out, $25 to purchase) and is made by Rogue Amoeba. It’s very simple to install and run. When I tried playing a DVD, though, the audio didn’t synch properly with the video.

This is the solution I found to fix the audio synchronization problem using VLC to play back the DVD and by adjusting the preferences and using VLC’s ability to buffer audio and adjust the synchronization settings.

How to increase audio buffering amount in VLC for DVD playback

  1. Open preferences in VLC
  2. Click on Advanced tab on bottom of screen
  3. Select Input/Codecs
  4. Select Access Modules
  5. Select DVD with menus [Note: to make this same adjustment when you are playing back regular files as opposed to DVDs, simply select File instead of DVD with menus and continue with the rest of the instructions]
  6. Change the default value (300 milliseconds) to 6000. This will increase the amount of audio data buffering to 6 seconds, which should be enough to synchronize the audio playback.
  7. Click Save to activate your changes (you may need to quit VLC to ensure the settings become active).
  8. Re-open the DVD using VLC and click Play.
  9. Click the “f” key repeatedly to adjust the amount of audio synchronization offset. It adjusts the audio offset downwards by 50 millisecond increments. I had to set mine to around -4900 milliseconds to correctly match the audio with the video output on my system. Press the “g” key to increase the offset in the other direction. Watch the actor’s lips and adjust the offset until it matches perfectly.
  10. Enjoy listening to your DVD audio through your speakers, streamed wirelessly!

Hacking the Gibson

Download VLC (Free Open Source video player)

Download Airfoil

WP-Cache 2.0 – useful for surviving the digg/reddit effect for your WordPress blog

WP-Cache 2.0 – useful for surviving the digg/reddit effect for your WordPress blog

Found this useful plugin from this site while working on a site that was in the middle of getting dugg/reddited:

WP-Cache is an extremely efficient WordPress page caching system to make your site much faster and responsive. It works by caching Worpress pages and storing them in a static file for serving future requests directly from the file rather than loading and compiling the whole PHP code and then building the page from the database. WP-Cache allows to serve hundred of times more pages per second, and to reduce the response time from several tenths of seconds to less than a millisecond.

Get the plugin here: Ricardo Galli, de software libre – WP-Cache 2.0

Some excellent WordPress plugins I found recently – Breadcrumbs and better Links page management

Some excellent WordPress plugins I found recently – Breadcrumbs and better Links page management

I’m working on a new site relating to Gramm-Leach-Bliley Act compliance (it will replace the useless site that is currently up at grammleachblileyact.com) and was looking for breadcrumb functionality and a better way to manage outputting links from the Blogroll on the links.php page.

I had searched for a good WordPress breadcrumbs plugin a while ago, and the ones I found didn’t really impress me. I’m really happy with the one I ended up finding this time. It’s called Breadcrumb Navigation XT and it does exactly what I was looking for. I’ll be using this probably for any future needs when it comes to breadcrumbs and WordPress.

The second plugin that I found was related to fixing how WordPress currently outputs links using the default get_links_list() function used in most links.php template pages right now. I had used on the XyzAnt.com links page another WordPress function (wp_list_bookmarks()) that only works for WordPress 2.1 and higher, and is still undergoing active development / documentation. That function, however, only allows you to output the description, and doesn’t appear to include the functionality to show notes. Since there is a larger amount of allowable text for the notes field, and that is what I needed, I still needed to find (or write) a solution to outputting all links, ordered by category, displaying the notes field as well as link title, url, image, etc. This is the plugin that I found that does just this (found it after writing about 80% of the same functionality myself). It does just what I was looking for, shows all the categories that contain links and the links within each category.

Plugin author’s latest post about WordPress 2.1 support: Link Library now supports WordPress 2.1

DiddleBug Extractor 2.1 – Palm DiddleBug image extractor script for OS X, Windows, Linux (Replaces Didcon 2.0)

DiddleBug Extractor 2.1 – Palm DiddleBug image extractor script for OS X, Windows, Linux (Replaces Didcon 2.0)

DiddleBug Extractor 2.1

DiddleBug drawing - crow

Drawing pictures on your Palm

I use an excellent free Open Source program called DiddleBug on my Palm Treo 700p for doing small black and white drawings. The latest version of DiddleBug creates 320×320 pixel size drawings. These are referred to on their site as “high-res” pictures instead of the 160×160 pixel size drawings that older versions of the software created.

Getting DiddleBug pictures off your Palm

I used to use a nice converter on my Windows laptop called WindleBug but wanted to be able to just use my Mac laptop by itself instead.

The DiddleBug FAQ mentions using a Perl script called Didcon on Windows, Linux and OS X which hadn’t been updated yet to extract the new 320×320 pixel sized images. When I ran the Didcon script for the first time, it saved out a 160×160 graphic that had weird lines running throughout it, due to the fact that it wasn’t reading out the data for a 320×320 pixel sized graphic.

After hacking at it for a little while, including researching how to correctly indicate the pixel size of an image in a Windows bitmap in the header of the file, I managed to get a working script that correctly outputs a 320×320 .bmp file.

This is the modified script, and I’m also including a second script that you can double-click in the Finder to run the extraction process.

Read More Read More

Chickenfoot – Firefox extension to automate web tasks with Javascript in your browser

Chickenfoot – Firefox extension to automate web tasks with Javascript in your browser

This looks pretty neato.

Chickenfoot is a Firefox extension that puts a programming environment in the browser’s sidebar so you can write scripts to manipulate web pages and automate web browsing. In Chickenfoot, scripts are written in a superset of Javascript that includes special functions specific to web tasks.

Check it out: Chickenfoot

(Via the Lifehacker RSS feed at RSS2.com)