Categories
Package/plugin/module WordPress

Plugin: Get Custom Field Values

This plugin has been updated! Comments to this post are now closed. For the latest download, documentation, and link for posting new comments related to this plugin, visit the plugin’s new homepage at:
coffee2code.com/wp-plugins/get-custom-field-values
Name:
Get Custom Field Values
Author:
Scott Reilly
Version:
2.1
Last updated:
26 March 2005
Description:

Easily retrieve and control the display of any custom field values/meta data for posts, inside or outside “the loop”. The power of custom fields gives this plugin the potential to be dozens of plugins all rolled into one.

Notes:

This is a simple plugin that allows you to harness the power of custom fields/meta data. You can define $before and/or $after text/HTML to bookend your results. If no matching custom field by the name defined in $field was found, nothing gets displayed (including no $before and $after) (unless $none is defined, in which case the $none text gets used as if it was the match). If multiple same-named custom fields for a post are defined,only the first will be retrieved unless $between is defined, in which case all are returned, with the $between text/HTML joining them). If $before_last is defined along with $between, then the text/HTML in $before_last is used prior to the last item in the list (i.e. if you want to add an “and” before the last item). Head down to the Tip & Examples section to see how this plugin can be cast in dozens of different ways.

Installation:
  1. Download the file get-custom.zip and unzip it into your wp-content/plugins/ directory.
    -OR-
    Copy and paste the the code ( get-custom.phps ) into a file called get-custom.php, and put that file into your wp-content/plugins/ directory.
  2. Optional: Add filters for ‘the_meta’ to filter custom field data (see the end of the file for commented out samples you may wish to include) *NEW*: Add per-meta filters by hooking ‘the_meta_$field’
  3. Activate the plugin from your WordPress admin ‘Plugins’ page.
  4. Give a post a custom field with a value.
  5. Use the function c2c_get_custom somewhere inside “the loop” and/or use the function c2c_get_recent_custom outside “the loop”; use ‘echo’ to display the contents of the custom field; or use as an argument to another function
Functions:

function c2c_get_custom ($field, $before='', $after='', $none='', $between='', $before_last='')

  • $field : This is the name of the custom field you wish to display
  • $before : The text/HTML to display before all field value(s)
  • $after : The text/HTML to display after all field value(s)
  • $none : The text/HTML to display in place of the field value should no field value exists; if defined as ” and no field value exists, then nothing (including no $before and $after) gets displayed
  • $between : The text/HTML to display between multiple occurrences of the custom field; if defined as ”, then only the first instance will be used
  • $before_last : The text to display between the next-to-last and last items listed when multiple occurrences of the custom field; $between MUST be set to something other than ” for this to take effect

function c2c_get_recent_custom ($field, $before='', $after='', $none='', $between='', $before_last=', ', $limit=1, $unique=false, $order='DESC', $include_static=true, $show_pass_post=false)

  • $field : This is the name of the custom field you wish to display
  • $before : The text/HTML to display before all field value(s)
  • $after : The text/HTML to display after all field value(s)
  • $none : The text/HTML to display in place of the field value should no field value exists; if defined as ” and no field value exists, then nothing (including no $before and $after) gets displayed
  • $between : The text/HTML to display between multiple occurrences of the custom field; if defined as ”, then only the first instance will be used
  • $before_last : The text to display between the next-to-last and last items listed when multiple occurrences of the custom field; $between MUST be set to something other than ” for this to take effect
  • $limit : The number of recent custom field values you want returned; default is 1
  • $unique : Boolean value (either ‘true’ or ‘false’) to indicate if only the latest instance of $field should be considered, and subsequent occurances of $field would be skipped in the search; default is ‘false’
  • $order : The order the results should be returned, either ascending/increasing (‘ASC’) or descending/decreasing (‘DESC’); default is ‘DESC’
  • $include_static : Boolean (‘true’ or ‘false’) to indicate if static posts (i.e. “pages) should be included when retrieving recent custom values; default is ‘true’
  • $show_pass_post : Boolean value (either ‘true’ or ‘false’) to indicate if passworded posts should be considered in the search; default is ‘false’
Tips & Examples:

Do you simply want to retrieve the value of a custom field/meta data?

<?php echo c2c_get_custom('mood'); ?>


Want a moods plugin?

<?php echo c2c_get_custom('mood', '(Current mood : ', ')'); ?>

Example results:
[if ‘mood’ is set to ‘happy!’] (Current mood: happy!)
(add filters if you wish to use smilies, etc)


Want a currently reading/currently listening to plugin?

<?php echo c2c_get_custom('reading', 'Currently reading :'); ?>

[if value for ‘reading’ is ‘Cujo’] Currently reading: Cujo

<?php echo c2c_get_custom('reading', 'Currently reading: <i>', '</i>', '', '</i>, <i>'); ?>

[if three ‘reading’ fields were defined, with values ‘Carrie’, ‘Cujo’, and ‘The Shining’]
Currently reading: Carrie, Cujo, The Shining

<?php echo c2c_get_custom('listening', 'Now playing ', ' on my stereo.', 'nothing'); ?>

[if value for ‘listening’ is ‘The Beatles’] Now playing The Beatles on my stereo.
[if no value defined for ‘listening’] Now playing nothing on my stereo.


Want a Post Icon plugin (image to display for the post, not derived from category)?

<?php echo c2c_get_custom('post_icon', '<img alt="post icon" class="posticon" src="/wp-images/posticons/', '.gif" />', 'blank'); ?>

[if value for ‘post_icon’ is ‘wordpress’]
<img alt=”post icon” class=”posticon” src=”/wp-images/posticons/wordpress.gif” />


Want to do per-post customized ‘more’ text? (to override the default “(more…)”) (This example will show the default “(more…)”, which you can of course change, if you don’t define the custom field ‘more’ for a post)

In index.php, look for this function: <?php the_content(); ?>

Replace it with this:

<?php the_content(c2c_get_custom('more', '<span class="more">', '</span>', '(more...)')); ?>

Related Links:
  • WordPress Support Forums announcement of Get Custom Field Values
Release Log:
  • 26 Mar 2005 : v2.1 released —
    • Removed the $filter argument from c2c_get_custom() and c2c_get_recent_custom()
    • Replaced $filter argument with more robust filtering approach: filter every custom field via the action ‘the_meta’, filter specific custom fields via ‘the_meta_$field’
    • Add argument $include_static (defaulted to true) to c2c_get_recent_custom(); static posts (i.e. “pages”) can be optionally excluded from consideration
    • Verified to work for WP 1.5 (and should still work for WP 1.2)
  • 08 Sep 2004 : v2.01 and v.202 release — minor bugfixes
  • 07 Sep 2004 : v2.0 released :
    • Added the new function c2c_get_recent_custom() that allows retrieving custom/meta data from outside “the loop”
    • Better filtering (on meta field itself instead of final output string)
    • Per-call filtering of meta fields
    • Prepended all functions with “c2c_” to avoid potential function name collision with other plugins or future core functions… NOTE: If you are upgrading from an earlier version of the plugin, you’ll need to change your calls from get_custom() to c2c_get_custom()
    • Changes to make the plugin WordPress v1.3 ready (as-yet unverified)
    • Switched to MIT license
  • 22 Jul 2004 : v1.0 released — added argument of $before_last (which, went $between is also defined, will be used to join the next-to-last and last items in a list); added invocation of an action called ‘the_meta’ so that you can do add_filter(‘the_meta’, ‘some_function’) and get custom field values filtered as they are retrieved; to faciliate use of this plugin as the argument to another function, this plugin no longer echoes the value(s) it retrieves (user must prepend ‘echo’ to the call to get_cust())
  • 30 Jun 2004: v0.91 bugfix release
  • 30 Jun 2004: v0.9 released to the public
Copyright & Disclaimer:

Copyright (c) 2004-2005 by Scott Reilly (aka coffee2code)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Acknowledgements:
N/A

252 replies on “Plugin: Get Custom Field Values”

Method of handling replies
Because (slight) interest has been expressed in the way I display replies to comments, and (slight) interest has been expressed in the method I used to set it up, I figured I should post the steps I took to make it how it is. All the code used here was…

B.A.R.: Have you tried adding the new custom field and then clicking “Save” or “Save and Continue Editing” for the post instead of the “Add Custom Field” button? That might work for you.

Andrea: I’m not sure exactly what you’re asking… do you mean somehow change the ‘before’ and ‘after’ text depending on something else? If so, yes. For instance, in index.php (if you are running 1.2.x) you could do something like:

<?php
 if ($single) {
    $before = "before1';
    $after = 'after1';
 } else {
    $before = 'before2';
    $after = 'after2'; 
 }
 echo c2c_get_custom('some_field_key', $before, $after);
?>

That would use ‘before1’ and ‘after1’ on the permalink page, and ‘before2’ and ‘after2’ on all other pages (the index, archives, etc).

Unless you really just meant using ‘some_field_key’ multiple times, via numerous calls get c2c_get_custom(), but with different before/after text. If so, that is valid also.

If I’ve failed to answer your question feel free to try me again.

Oops, sorry for not being more specific. I meant the latter (although I’m curious to see the code you provided, it’s invisible in your comment), and an example–although not what I had in mind when I asked the question–would be

<?php echo c2c_get_custom('picture', '<p><a href="http://blog.com/files/', '">', ''); ?>
<?php echo c2c_get_custom('picture', '<img src="http://blog.com/files/', '" height="160" /></a></p>', ''); ?>

for creating a thumbnail. Should have tried it out before asking, works like a charm. 🙂

(This is a bit off-topic, but I’ve tried the WP support forum and haven’t got an answer so far, so maybe you can help? I’m making extensive use of the custom fields, and everytime I create a new key, one key is kicked off the dropdown-menu, keeping the number of menu items always at 10. I have to retype keys I had created earlier, because they vanish from the list. Are you familar with this? Do you happen to know a fix?

Thanks in any case.)

Andrea: So you’re all set with the use of the plugin?

As for your WP question, I looked into it and saw where the “problem” is located. The list of custom field keys is limited to 10, as you discovered. It’s hardcoded, so to change it you’ll need to modify a WP file. Look at the file wp-admin/admin-functions.php and search for “function meta_form”. In that function you’ll see a bit that says LIMIT 10. Change the 10 to another number to up the number of keys presented in the list.

Your support request gave me the idea to address that issue, and some others, in a new custom field manager plugin that I already had plans to create soon.

I just replied to my own post in the support forum. Found the code all by myself (I’m so proud) and increased the LIMIT value. Thanks very much for looking into it, anyway. 🙂

And yes, all set. You could also say, “addicted”. It lets me add bibliographical data, internal and external links and pictures to my little archive and easily control the presentation of that data by shuffling around some lines of code in the index file (and CSS, of course). Gush, gush, gush. 🙂

The only problem right now is that I’m displaying most of the meta in a sidebar outside The Loop, so it messes up the layout a bit on pages that display more than one post. I’m waiting for the release of a stable 1.3/1.5 to set up templates for different kinds of pages, until then I can put up with that little inconvenience.

Hi, just wanted to let you know that I got rid of the problem mentioned in the last paragraph above by restricting the display of outside-the-Loop metadata to pages that contain only one post. A kind soul helped me with the necessary PHP stuff.

Strange, but true. I don’t know if anyone else is experiencing this but figured this place would be the best to ask.
I am trying to used this with the “Vesuvius WordPress Interface 1.20” – the plugin works great in the main section, but fails to show anything in the right panels.
I am using the same code both times, just different

location.

Any ideas? Anyone else experience this in the Vesuvius template?

Fantastic plug-in.

A quick question: I have put in a rather long article on the custom field, and it presents it and all. However, the hard breaks at the end of lines are eliminated, and the whole article becomes one long run-on series of sentences. How could I make it preserve the hard returns? I’ve looked at filters, but it seems somewhat confusing as the documentation in them in wordpress appears a little limited.

Thanks very much for your help.

A closely related question: is there a way to make a little link appear, which when you click suddenly opens a simple window with just the content of the custom field? I’m planning to paste an article in the custom field so you can imagine where this is going…

Thanks again!

I just installed this under wp1.5 but I can’t get it to work – nothing is showing up.

I added a key called mood with a value of happy.

<?php echo c2c_get_custom('mood'); ?>

I added that within the lopp but nothing is showing up. Anyone get this to work under 1.5?

Jonah: I haven’t used Vesuvius and haven’t had anyone report a problem.

Stephen: This plugin supports filters specifically geared toward custom fields, however, in its current implementation it applies the filter(s) to all custom field values, not just any specific one. So one suggestion would possibly be to use WP’s wpautop (i.e. add add_filter('the_meta', 'wpautop'); to the filter section at the end of the plugin file), but that may adversely affect the display of other custom fields, if you use and display others. I’ve now added a task to my ToDo list to allow more fine-grain filtering of particular custom fields.

As for your popup request, it can certainly be done, but requires more time to explain than I can currently give. Someone on the WP support forums might be able to answer your question.

Michael: I hadn’t tested it on WP1.5 despite having made what I thought was the necessary changes to have it work under 1.5. Since you said something, I went and looked and spotted a problem for the c2c_get_recent_custom() function:

if (!isset($tableposts)) {
  $tableposts = $wpdb->tableposts;
  $tablepostmeta = $wpdb->tablepostmeta;
}

should be:

if (!isset($tableposts)) {
  $tableposts = $wpdb->posts;
  $tablepostmeta = $wpdb->postmeta;
}

However, that doesn’t explain why c2c_get_custom() wasn’t working for you. Later tonight I’ll test it out on my test WP1.5 install.

I’m trying to use this plugin to automate a user picture since I have 2 authors on my site. Is there anyway I can incorporate the php for the author along with this plugin so that it’ll read which author it is and automatically give it the corresponding image? I got it working with the custom field value, but for that, I’d need to go in and manually set the pic everytime instead of having it automatically read.

Lawrence: If you can wait about a week, I’ll probably releasing a plugin that handles author images in an automatic, and also configurable, manner. I actually have it completed already, but have to do the mundane things related to actually releasing a plugin. Plus, it’s part of a more concerted plugin-release plan! 😉

Do you happen to be running WP 1.5? My plugins are all going to be geared toward 1.5 from now on, though this particular one could be backported fairly easily.

Just wanted to say thanks for this marvelous plugin working perfectly with 1.5 and no modification.
Still haven’t figured out the “outside the loop” stuff but I’ve got it inserting titles, texts and pics in my sidebar.

Wow, what an incredible plugin! I’m running WP 1.5 (brand new to it, btw) and installed 2.02 of this plugin per instructions, but when I active it, I get this error message in the /wp-admin/ header:

Warning: Cannot modify header information – headers already sent by (output started at /home/ozaaxuly/public_html/wordpress/wp-content/plugins/get-custom.php:181) in /home/ozaaxuly/public_html/wordpress/wp-admin/admin.php on line 6

Very unsightly in admin dashboard. Posted web pages are okay. Hesitant to try the function, and deactivating for now.

djchuang: That error most often means that there spaces or other characters before the at the start of the file or after the <code>?&gt;at the end of the file. Check to make sure there aren’t any such extraneous characters.

Scott – thanks for the quick response, and didn’t know PHP files were so sensitive to extraneous chars. Your suggestion fixed it, and the plugin works like a champ! Great work, thank you!

not sure if you think there’s a way to do this. I installed the plugin and got the basic features working to give me a “subtitle” for some pages (not posts, I’m using wp 1.5). what I’d like to do is use this subtitle in the “get pages” loop so that the subtitle also displays in my navigation. any ideas? I tried appending the subtitle in the list pages function, but I get the subtitle of the page I’m on, not of the page in the navigation loop… is there a way to direct the function to check a specific page and not the current one? I’m just getting my feet wet with php and wordpress, but I am a web developer and the basic concepts are the same as other languages I’ve used…

Im using this on my site with WP version 1.5 It seems to work ok except i used it to call my mood plugin. I placed the c2c call code inside my index.php page. I put it in the wrong place and so i moved the code lower so it would show up after my postings and not before. But it doesnt seem to want to move. Even after i moved the code and updated my page its still showing up right beside the date. Ugh! What do i need to do to fix this??

Ditto the above 2 people. I would also like to know how to include the info stored in the custom fields to show up in the search results.

Hi Scott,
I would like to know is possible to use this plugin for calling two type of images to a post? For example on my regular post on the frontpage (index.php) which has several posts. If a visitor click on the title link it will bring them to a full single post which has a full size image on single page with all the text of the post, instead of small image on the frontpage.

Thank you

~Rocky

I’m looking to use this plugin to display a set of custom field values in each post. Before doing that, i need to have the custom fields be fixed on each edit-form.php page, not simply for a single post. This post looks helpful, except it was for 1.2, and i dont know if the code needs redoing.

I have tried, and still am, to incorporate multiple inputs such as the content etc.. but am not getting very far with it.

Any help would be greatly appreciated

Thanks,
Amory

shawn: Still looking for an answer for your request?

Java Where precisely did you move the c2c_get_custom() function?

trench: Yep, you can use HTML in custom fields. For something like an image, it depends on how you want to reference them. Are they always in the same directory? If so, send the link tag stuff in the $before and $after arguments and just put the image name in the custom field.

<?php echo c2c_get_custom('image', '<img src="http:// www.7milesdown.com/wp-content/images/', '" />'); ?>

Otherwise, put the full path in the custom field and omit the directory information from the $before text.

Ross, Nessie, hcm: Yes, currently WP does not search into custom fields. And for various reasons, it may never. The trouble is that not all custom fields are meant to be publically available.

Rocky: With a small bit of coding you can accomplish that. Here’s an example (which may not be exactly what you wanted):

In index.php where you want the image to appear (I’m assuming the small and large images are to appear in the same spot:

<?php 
$size = is_single() ? '' : '-sml';
echo c2c_get_custom('post_icon', '<img src="/wp-content/images/', "$size.jpg\" />");
?>

Assumptions:
* Large and small image show up at same spot in post
* Large image appears on single page; small appears on all others
* Image filename in is ‘post_icon’ custom field
* Image location is /wp-content/images/
* Large file is something like myimage.jpg
* Small file has same name, but with “-sml”: myimage-sml.jpg

There are a ton of other ways to do this though.

Scott,

I put this code “”);
?>” in my index.php page and when I write a post I insert the “myimage-sml.jpg” in the post. In the images directory there are also the file “myimage.jpg”

I also add the “post_icon” in the custom field when I write the post. But the post and the single page show the same image, instead of the small and large in teh single post. What other steps have I miss?
Thanks

Scott, look like WordPress strip my the code from the post. Anyway is the code you post for me. How do you put code to showup in the post anyway?
Thanks

From the perspective of your close knowledge of the custom tags implementation, have you been thinking of a mechanism allowing to posts by the value of one of their custom tags?

This would make “timed” posts possible – which is now not possible as we can not create a post with a set date.

I know that this would have to influence the Loop and maybe override some of the sorting functions in it but would be very valuable and provide great flexibility.

Bonus functionality would be to:
– only show posts with a certain value in a custom field
– only show posts with a certain metadata key filled in

Thank you.

Scott,

First of all, thanks for writing this. It may save me some time with a current project, but even if it doesn’t I can see all sorts of uses for it.

Second, I want an array of values for a given field so I can play with the data in php. Possible currently? If no, I’ll hack my own. I haven’t gotten into the code yet to see how this works.

Thanks.

        $mylistens= c2c_get_custom('mylisten');
                    $boollisten=$mylistens[0];
                     if (!empty($boollisten)) {
                          echo c2c_get_custom('mylisten', ' who is listening to  ', '',          
                          'nothing.');
                       } 

my earlier post left on the question mark php stuff and isn’t showing up.

Comments are closed.