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”

This plugin looks very nice. I think it’ll enable me to have a blog with different times… in multiple time zones (different posts display different time zones—and locations).

But (because I’m such a know-nothing when it comes to PHP) I don’t know how to get from creating the custom field tz with, say, a value of -6, and from there calculating to make the time displayed in that post to be accurate for the local time zone. (Do I create a new time variable $time_zone_time ? Or do I perform some calculations based on the value in ‘tz’ and then manipulate or pass something to the the_time() tag?)

I’ve also queried on WordPress support board in this post.

Hello,

I’m using this plugin in WordPress (WP 1.5.1.3) for an events site, and it gives loginproblems. Whenever I activate the plugin I can’t logout anymore and only get to see blank pages throughout the site (wp-part => blank login, blank admin, blank post etc.), except for the blog itself. When I remove the plugin from the plugins folder everything is OK again. Also when I upload the file again but leave it deactivated no harm is done. But activating it will close all acces to WP.

Any idea? (I’m not using any other plugin).

Jack

I noticed there was 1 space behind the last ?> php-code. I removed it and (untill now) it seems to be working again.

Can 1 space really make the difference?

Hi there…

This is a great plugin, Scott. Many thanks!

I have a question about the sample code you posted above…

', 'blank'); ?&gt;

I find this works correctly for the first page (e.g., example.com/), but for subsequent pages (e.g., example.com/page/2/) I just get the ALT text.

I can correct this buy specifying the full path to the icon in the SRC attribute (e.g., src=”http://example.com/wp-images/posticons/”, but it doesn’t work with src=”/wp-images/posticons”. I’m not very knowlegeable about PHP. Is there another way of using the WP tag that would work here?

Hi Scott,

In scanning through this page I noticed a request from Joey Horne on October 19, 2004 that is similar to what I want to do.

You later indicated that it could be done, but I have not been able to find any further reference to it.

I want to filter my Comments on my Static Pages. (Not Posts).

For example, I would like users to be able to filter comments based on, say, the Commenting Members zip code (entered in the Custom field at the time of comment) or their own zip code. (Or can this be done dynamically from the WPDB through your plug in?)

But this would also be cool for say Posts to a ‘what’s on’ blog so that user’s could see ‘what’s on’ for a particular Geographical area.

The ability for them to edit a preference to “retain” the filter during subsequent visits through either cookies or your plug-in would be nice – so long as they can override those preferences at any time ‘on-the-fly’ or to change and re-set them.

Aplogize for the long shopping list – seems like your plug-in may help but I am lost on how to make it work.

TIA

Hi Scott,

In scanning through this page I noticed a request from Joey Horne on October 19, 2004 that is similar to what I want to do.

You later indicated that it could be done, but I have not been able to find any further reference to it.

I want to filter my Comments on my Static Pages. (Not Posts).

For example, I would like users to be able to filter comments based on, say, the Commenting Members zip code (entered in the Custom field at the time of comment) or their own zip code. (Or can this be done dynamically from the WPDB through your plug in?)

But this would also be cool for say Posts to a ‘what’s on’ blog so that user’s could see ‘what’s on’ for a particular Geographical area.

The ability for them to edit a preference to “retain” the filter during subsequent visits through either cookies or your plug-in would be nice – so long as they can override those preferences at any time ‘on-the-fly’ or to change and re-set them.

Aplogize for the long shopping list – seems like your plug-in may help but I am lost on how to make it work.

TIA

Hi Scott,

I’m wondering if this might be useful for pulling the contents of meta fields within pages into the wp_list_pages function. I’m hacking together something where I’d like to be able to list those pages by data stored in the meta fields, and this might do it.

Unfortunately, I seem to be getting errors when I try to activate the plugin, so I haven’t yet been able to check it out.

Does this sound like something this can do – i.e., pull custom fields from multiple pages that you’re not presently on?

Thanks,
Jeremy

Hi Scott,

Thanks for this amazing plug-in. I have a question for you, that is sort of answered in Post #81, but I still can’t figure it out. Here is what I am looking to do: I would like a small graphic to show up and be linked to something (say, a popup window). Is there a way to add an href link into Value field of a custom key?

Thanks for any help, Jesse

scott-

very nice plug-in. although i’m wondering if the plugin is the way to solve my situation…maybe you can help. i’m wanting to run a poll on certain posts tied to the post…what i do is create my poll which assigns it an id#. i have the poll code inserted into my post-template to display the poll…when i add a post, i select a key named ‘poll’ and then input the value (#) that corresponds to what poll I want to display on that post. i’m using Advanced Poll 2.03.

here’s the line of code I need to be dynamic because if it’s static then the same poll is displaye on all my posts since it’s in the post-template :

echo $php_poll->poll_process(4);

as you can tell above the number i need to have dynamic is the ‘4’…the post i’m working on i select the key named ‘poll’ and input a value of ‘4’…i then put the following code in my post-template.

echo $php_poll->poll_process();

…but the result I get is : Parse error: parse error, unexpected ‘poll_process(”);

…but the result I get is : Parse error: parse error, unexpected T_STRING in /home/mynotary/public_html/wp-content/themes/default/single.php on line 41

finally, i tried :

echo $php_poll->poll_process(echo c2c_get_custom(‘poll’));

…but the result i get is : Parse error: parse error, unexpected T_ECHO, expecting ‘)’ in /home/mynotary/public_html/wp-content/themes/default/single.php on line 41

any ideas or is custom-fields not the way to get what I need done? is there another way to achieve what i need? i’ve tried many resources for days now and have found no answer.

This plug-in is amazing. I have successfully incorporated it into 2 of my websites. I have ran into a problem though. For my latest site, I tried to use the plug-in with MULTIPLE LOOPS. What I’ve done is this:

is there a way to use TWO fields within the retrieve functions? I have two meta keys ‘news source name’ and ‘news source link’ for each of my posts….

Basically for my posts I want to give credit to a news story from the link I got it from, so in my posts template I would it to pull the news source name (if there is one, eg Fox news) and turn it into a link to the article (from the news source link). If there is no name and link then I don’t want anything to show??

Hi – is there any way to pass the value generated by c2c_get_recent_custom into a link that will automatically search WP entries for that value?

(I’ve altered my WP install so it searches custom fields, and I have verified that it works. I can generate a list of values from the c2c_get_recent_custom command, then copy/paste a value from the generated list into search and get the results I want. )

It works “by hand,” but the only thing I don’t know how to do is to make it so that when the list is generated, it automatically creates a link for each item on the list that, when clicked, would automatically perform a search and take the visitor to the search results page.

I understand if this can’t be done or if an explanation is beyond the scope of this forum, but figure it doesn’t hurt to ask. Thanks!

[…] I’d wanted to add a “via” attribute to the Dailies over there on the left, and the custom field in the post form is the perfect place for that. But I wasn’t quite sure how to alter the output of the the_meta(); tag. Fortunately, Scott Reilly at code2coffee has already written a plug-in to handle it. Yay! […]

I don’t know if anyone has ever had this problem, or know why this is happening, but when I have inserted custom meta data into my category loop, the appropriate data doesn’t always display.

I’m not a programmer, so I don’t know if this is strange or not. I’m running 3 loops on my categories page that filters posts according to certain custom data fields using two plugins (custom field gui and AH Select custom). That part is working fine (I think).

I also have meta data that displays custom field datausing the plugin. What’s strange is that in some of my posts, the meta value just doesn’t seem to get displayed. To see for yourself, check out:
radresearch1.odani.com/?cat=5 and
radresearch1.odani.com/?cat=6

Does anyone know how this might happen??

I would like to sort posts by the value of a particular custom field. There does not seem to be an easy way to do this. Though I realize this is outside the immediate scope of your wonderful plugin, it seemed like a good starting place to ask.

Perhaps there is a way to hack WP’s built-in query_posts(orderby) attribute, which only seems to support ‘author’, ‘date’ and ‘title’ as values.

(I’ve also posed the question in a bit more detail on the WordPress support forums.)

Thanks for any ideas or suggestions,
abrupt

I realize this is outside the scope of this plugin, but… I have a clip blog on my site, meaning that each post has (as a rule) a URL in the body. Right now, I generally post using the bookmarklet and bookmarklet.php, which puts the URL in the body (in my case, using Textile markup). What I’ve been trying to do is find a way to insert that URL into a custom field called clip_url instead. The reason I want to do this is, if I want to change the way the link looks after posting, there’s no easy way to do that right now. Since it’s part of each post’s body, it’s sort of static. Where if it were a custom field, I could simply edit the current theme to change the text of the link, the position of the link, etc…

Has anyone found a way to post custom links from the bookmarklet? I’ve made a few attempts to do this, but so far everything has failed. If I add the custom field by hand in the main post editor, everything works fine with the get custom field plugin… I just can’t convince the bookmarklet post method to stuff this value into a cusotm field for me 🙁

Might you have any explanation for why my new Custom Fields – after working normally for quite some time, and with your plugin – no longer get recorded in the database and so do not show up in the pulldown menu? I have searched the WP fora and posted the problem, but to date with no answers. Thanks for any help or suggestion. Regards

[…] Today’s Mood: Jolly and Happy y puedes darle un estilo usando css. Puedes encontrar m?s informaci?n aqu?: Using custom fields Al ponerme a usarlo me di cuenta que no me serv?a, ya que esos campos solo sirven para a?adir un contenido dentro de los posts, dentro del wp-loop. Yo necesitaba las variables para fuera del loop de los posts, para a?adir un bloque de contenido con un plugin en una plantilla. As? intentando solucionar este problema encontr? este plugin con el que puedes usar esos campos en cualquier parte de tu plantilla. El plugin se llama get custom value. Adem?s de los valores del campo puedes pasar html para poner antes y despu?s, asi que puedes darle tambi?n estilo tambi?n. […]

Hello, nice plugin 🙂

I’m trying to use it in conjuection with c2c_get_recent_posts but am not sure if it can work in this context?

Eg. I would like to add two custom field values to my sidebar, after the post URL which I’m pulling out like this:

Exhibitions

%post_URL%”, “4”); ?>

Is this possible, I’m not sure reading the above!???

Hi, maybe you already answered this question but I couldn’t find anything about it (maybe I just missed it). The point is: this plugin is absolutely great and I can manage all kind of custom fields when writing a POST… but not when I go to the “write / page” admin page in WP. Simply, it doesn’t show up.
I would like to add reviews of comics/movies, et-cetera, in my website, and I was loooking for some plugin that can help me manage in the WP admin the custom fields I need for those static pages (like: “Author” or “Title” or votes like “Screenplay: 70%” – “Special FX: 80%” and so on). They should be called in the sidebar IF they are present, of course, and your plugin seems to do just the right thing. Except, I can’t see it in the write/page interface…

Is there anyway to have posts ordered alphanumerically by the value of their custom fields?

As I understand it, they are now listed in either ascending or descending order by the date the post was created.

I’d like to use wordpress to create a historical timeline where each post describes an historical event.

I can’t just back-date the timestamp because many of the events are going to be hundreds of years in the past, and PHP and MySQL can’t handle dates that far back.

My plan has been to create three custom fields — year, month, and day — and have the posts sorted by each of those in turn.

Does that sound possible?

Hi, here again =)
I found out how to create a different sidebar with the contents I need, but the problem is that with c2c_get_recent_custom, if you write another review with all the data (director, cast, et cetera), this will overwrite every information in EVERY review page. And c2c_get_custom doesn’t work outside the loop. So, how can you add these custom fields in review pages in a way that can mantain individual specific data for each page?
Please, help me! =)

I don’t know whether this plugin is still being maintained, but I’ve found it incredibly useful. One small problem, though — it doesn’t appear to be compatible with 2.0RC1. I get ‘headers already sent’ errors all over the shop, one of which stops the image uploader on the post page from loading. My own fault for using a development version of WP, of course, but I thought I should let you know.

I had a SEO senstive customer who, after we launched the site, wanted to be able to customize the page name (in the title bar), the metatags for description and keywords. Of course only for some of the pages. This plugin saved me. The php code for description for example:


if (c2c_get_recent_custom('description'))
  {echo c2c_get_recent_custom('description');}
else
         {echo "default description for the whole site.";}

Thanks!

Okay, I spoke too soon. Seems that the latest pages they add the description too, it gets mapped to all the rest of the pages. Bummer. On a re-read of the page, seems you explained this. Hmmmm… off to think about this some more…

[…] 1) Das “Get-Custom” Plugin herunterladen. 2) Die Datei ins WordPress Plugin Verzeichnis kopieren. 3) Plugin aktivieren. 4) An der entsprechenden Stelle in seinem Template wo die Eingabe erscheinen soll (bei mir ist es die index.php) die Funktion aufrufen indem man folgende Zeile einfügt: < ?php echo c2c_get_custom (‘FELD’, ‘BESCHREIBUNG’); ?> […]

Hey Scott:

Great plugin. Many thanks.

I’m hoping you can direct me a bit. I’m needing to sort and display posts based on a particular custom field. Do you know of an easy way to do that?

A little background … I’m using your plugin as part of an RV dealership site (www.hiwaycampers.net) I built on WP. I want to create and print an inventory list sorted by the individual RVs’ stock numbers (a custom field I created).

Any help would be much appreciated.

Best – Michael

@Michael D. Pollock:

I’m needing to sort and display posts based on a particular custom field. Do you know of an easy way to do that?
the posts meta is stored in an array: $post_meta_cache.
See codex.wordpress.org/Plugins/Meta for more info on this. This lets you work with the values.

otherwise you could do what i did: i modified the “Search Everything” Plugin a bit, so that Wps’ Search function will look for a posts custom field values. Maybe thats a way to go for you (at least for diaplaying, not sure about order…) “Jerome’s Keywords” Plugin does something similar: it also searches the database for custom fields with the “keywords” key and displays results on a page /?tag=Tagged+with+This
you could adopt functionality from both of these Plugins…

@Scott Reilly: Thanks a lot for this Plugin!
regards

great plugin, just need some coding help.

When i add the custom field post_icon, i don’t want the words to appear i.e. “post_icon: happy”

but if i delete the php tag the_meta it doesnt make much sense, because other custom fields can’t be seen.

Comments are closed.