Simple Fields tutorial, part 2

In this tutorial I will show you how to access the fields we created in step 1 from within your templates. This is how they looked in case you don’t remember:

Ok, cool. Now there is actually a couple of different ways to fetch the selected values from the fields:

Method 1

Simple fields has it’s own function called simple_fields_get_post_value. It accepts three arguments: the id of the post we want to get the values for, the name or the id of the field that we wan’t to get the selected value from, and finally a boolean determin if the function should return all just the first value (useful if you have a field group with just one value) or all values for a field as an array (useful if you have a field group that is repeatable).

So if we for the current post in the loop want to get the selected color from the drop down box with the label/name “Color of box” we would use this code:

[php]
$selected_value = simple_fields_get_post_value(get_the_id(), "Color of box", true);
echo "The selected color is: $selected_value";
// outputs: "The selected color is: Green"
[/php]

Method 2

The above code has one big drawback: it requires you to enter the exact name of the field. So if you later on decide that a better name for the field would be “Box color”, then the above code would stop working. Ouch! That’s why I made it possible to pass on an array as the second argument. The array consist of the id of the field group and the id of the field. You can get the field group id and field id by clicking the “Show custom field keys”-link as shown here:

And that will result in the following info being shown next to each field:

Now we can see that “Color of box” has field group id 8 and field id 3. Good, that’s all we need.

Using this info in our example code would look like this instead:

[php]
$selected_value = simple_fields_get_post_value(get_the_id(), array(8, 3), true);
echo "The selected color is: $selected_value";
// outputs: "The selected color is: Green"
[/php]

Same result as the first example, but a bit more fail safe.

Method 3

It’s also possible to use WordPress’ own function get_post_meta.

That code would look like this:

[php]
$selected_value = get_post_meta(get_the_id(), "_simple_fields_fieldGroupID_8_fieldID_3_numInSet_0", true);
echo "The selected color is: $selected_value";
// outputs: "The selected color is: Green"
[/php]

The major drawback with this approach is that if we use repeatable field groups, we are unable to get all values at the same time. Other than that it should be fine.

Method 4

We can also get all values for all fields in a field group at the same time using the function simple_fields_get_post_group_values($post_id, $field_group_name_or_id, $use_name = true, $return_format  = 1).

This approach may be a bit more complex, so it may be targeted mostly at you advanced users out there. Also, it’s most useful when you are using repeatable field groups, as it returns an array that is very suitable to loop through in different ways.

I’ll just show you some quick examples here and then you can try it out yourself instead.

[php]
$selected_values = simple_fields_get_post_group_values(get_the_id(), "Options", true, 1);
print_r($selected_values);
/*
Output:
Array
(
[Show a share-button] => Array
(
[0] => 1
)

[Display a box with related posts] => Array
(
[0] => Yes
)

[Color of box] => Array
(
[0] => Red
)

[File] => Array
(
[0] => 0
)
)
*/

$selected_value = simple_fields_get_post_group_values(get_the_id(), "Options", false, 1);
/*
Array
(
[1] => Array
(
[0] => 1
)

[2] => Array
(
[0] => Yes
)

[3] => Array
(
[0] => Red
)

[4] => Array
(
[0] => 0
)
)
*/

$selected_value = simple_fields_get_post_group_values(get_the_id(), "Options", true, 2);
/*
Array
(
[0] => Array
(
[Show a share-button] => 1
[Display a box with related posts] => Yes
[Color of box] => Red
[File] => 0
)
)
*/

$selected_value = simple_fields_get_post_group_values(get_the_id(), "Options", false, 2);
/*
Array
(
[0] => Array
(
[1] => 1
[2] => Yes
[3] => Red
[4] => 0
)
)
*/
[/php]

That’s it! Comments?

Ok, I know you have questions. Write a comment and I’ll try to anwer them as soon as possible.

47 thoughts on “Simple Fields tutorial, part 2

  1. Hi – love this and thank you – but quite possibly a stupid question (as no one else has asked it!) I am now getting the fields to show using method 2 and am not having any luck assigning a specific template to my custom post – – instead the fields show up on every single post page.

    The WordPress codex states that: “The theme system supports post types too, in the form of the single-type template. In the same way that posts are shown on their own page with single.php, custom post types will use single-type.php if it’s available. So for the above example, you could create a single-super.php file and the super posts would be shown using that template.”

    This doesn’t work for me. I am waaaay out of my depth here – any suggestions very welcome

    Regards
    Lynne

  2. Lynne, you can use a plugin to create types of posts, like “Custom post types ui”, just look in the plugin search of your wordpress installation.

    If not, you can use this webs for more information:

    http://www.packtpub.com/article/developing-post-types-plugin-with-wordpress

    http://www.wpbeginner.com/wp-tutorials/how-to-use-custom-post-types/

    http://wordpress.org/extend/plugins/custom-post-type-ui/screenshots/

    http://net.tutsplus.com/tutorials/wordpress/rock-solid-wordpress-3-0-themes-using-custom-post-types/

    ————

    you can edit directly single.php in your server (keep a copy of the original single.php)

  3. No matter what I try to use to display the custom fields, I receive this error message displayed 5 times:

    Warning: array_merge() [function.array-merge]: Argument #1 is not an array in C:\wamp\www\review-it\wp-content\plugins\simple-fields\functions_post.php on line 675
    Warning: array_merge() [function.array-merge]: Argument #2 is not an array in C:\wamp\www\review-it\wp-content\plugins\simple-fields\functions_post.php on line 675

    – I have a fresh install of WP3
    – I have tried all different ways of outputting.

    Any clues what can be wrong?

    • Hm, I think there could be several reasons for this. But it’s a bit difficult do debug.

      Have you managed to successfully add fields to your post? And then on the public side of your site you get this error?

      • Exakt! Eftersom tillägget klarar av repetetive field groups så är det för bra för att dissa innan jag försökt få igång detta.

        Jag skulle precis börja beskriva problemet mer ingående då jag testade att installera tillägget på en annan dator, då fungerade det klockrent! Jag kör lokalt med WAMP så jag kanske har en äldre version av WAMP på den andra datorn?

        • Upprepningsbara fält rockar! 😉

          Bra att det löste sig. Om du kommer på sådär i sömnen eller nåt vad det var som skillde sig mellan WAMP:arna så berätta gärna!

          • Japp, det gör dem!

            Nu har jag hittat vad som är fel, det var inte WAMP:en utan IE8 som orsakar buggarna.

            Jag har hittat en del olika problem med IE8 på Windows.

            Jag skapade två Field Groups.
            – Testimonials (Upprepningsbart)
            – Facts (3 olika textfält)
            Samt en Post Connector som jag kopplade till Posts.

            1) Klickar man på “Show custom field keys” länken på posts sidan så visas bara Meta key: på en fältgrupp. Klickar man på länken igen så visas Meta key: på den andra fältgruppen och den första försvinner. etc.

            2) Ibland sparas inte värderna som man fyller i de olika fälten.

            3) Den buggen som skapar mest oreda är under Post Connector details. När man väljer en fältgrupp så adderas den valda gruppen, men under den valda gruppen läggs ytterligare en box med Add field group… till. Sparar man detta och går ut Simple Fields admin och sedan tillbaks så har dessa förökats ytterligare.

            Jag har lite skärmdumpar om du vill att jag ska maila till dig? Den fungerar dock utmärkt på FF/Windows.

            Tack igen för en riktigt bra plug!

            /Johan

            • En annan sak: Jag har inte kvar utskriftproblemet när jag administrerar sidan med FF.

            • Tack för feedbacken. Jag har själv inte testat pluginen alls i IE. Det står på min att-göra-lista men jag orkar liksoma aldrig ta tag i det, antagligen just fär att jag vet att det är saker som inte kommer att funka 🙁

    • Maybe change rows in functions_post.php to:

      //foreach ($one_field_group[“fields”] as $one_field) {
      foreach ($one_field_group as $one_field) {

      //$selected_post_connector[“field_groups”][$one_field_group[“id”]] = array_merge($selected_post_connector[“field_groups”][$one_field_group[“id”]], $field_groups[$one_field_group[“id”]]);
      $selected_post_connector[“field_groups”][$one_field_group[“id”]] = array_merge((array)$selected_post_connector[“field_groups”][$one_field_group[“id”]], (array)$field_groups[$one_field_group[“id”]]);

  4. Hej Pär!

    Skrev tidigare till dig angående ditt plugin. Jag har stött på ett nytt problem – försöker generera en XML feed från en custom post type i WP. Jag får ett felmeddelande när jag försöker kalla på ett Simple Field-fält,

    Fatal error: Call to undefined method stdClass::get_post_meta()

    Har även försökt att använda mig av simple_fields_get_post_value() men får samma resultat.

    PHP-koden är relativt simpel:

    require_once( ‘../../../wp-config.php’ );
    query_posts( ‘&post_type=products&post_status=publish&order=DESC’ );
    $xml = ”;
    $xml .= ‘<products';

    if( have_posts() ) : while( have_posts() ) : the_post();

    $xml .= '’;
    $xml .= ‘post_title . ‘]]>’;
    $xml .= ‘simple_fields_get_post_value(get_the_id(), array(1, 1), true) . ‘]]>’;
    $xml .= ” . get_permalink() . ”;
    $xml .= ” . $post->the_content . ”;
    $xml .= ” . $post->simple_fields_get_post_value(get_the_id(), array(1, 2), true) . ”;
    $xml .= ” . $post->simple_fields_get_post_value(get_the_id(), array(1, 3), true) . ”;
    $xml .= ” . $post->simple_fields_get_post_value(get_the_id(), array(1, 4), true) . ”;
    $xml .= ”;
    endwhile; endif;

    $xml .= ”;
    echo $xml;

    Ser du vad som kan vara felet?

  5. Hey, nice work on this plugin.

    Would be nice with some more detailed
    examples for the uses of dropdown menu, images etc.

  6. Hello Pär,

    you would give me a big favor if you could describe how i can output the fields of a repeated group.

    I tried to put them out with the example code above – i get the arrays but i dont know how to display only the fields…

    Kind regards,

    Christian

    • I have the same question! It would be really helpful if someone could post a code example for extracting the values from groups.
      Using example 4, I get a lot of extra stuff along with the actual values.
      Obviously, I’m not an advanced programmer. So a little help bridging the gap would be really appreciated. 🙂

  7. Hmm,

    not sure what’s going on. I get a complete array for

    $av = simple_fields_get_all_fields_and_values_for_post($post->ID);

    and also with the WP get_post_custom($post->ID) function, but I only get empty results for the single and the group query… say

    $sv = simple_fields_get_post_group_values($post->ID,
    1, true, 2);

    or

    $sv = simple_fields_get_post_group_values($post->ID, [group name], true, 2);

    All the variables are in this field group –

    “_simple_fields_fieldGroupID_1_fieldID_10_numInSet_0”

    What am I doing wrong? Thanks for a tip!

  8. I’m sorry but I’m not a PHP coder and need a hand, if it’s possible.
    I want use Simple Fields in a post where there is a mask with 6 icons that needs be connected to respective files (zip,pdf and so on) so I’d like to use SF to add 6 file browsers and obtain the file’s URL.
    All it’s ok, but I don’t know how to connect the results of file browsing to icons.
    I mean, there is some function that I can substitute to ?
    Of course, I need only code for one icon, after I’ll substitute IDs _simple_fields_fieldGroupID_1_fieldID_1_numInSet_0 for each others.
    Thanks in advance

  9. Absolutely Awesome plugin… But it did reek havoc on my admin panel:

    This is very important!

    In the plugin you are pulling in the jquery UI from google insecurely. On a secure site protected by SSL this sends an error message in the admin panel that “some things” are not secure and then clients get upset.

    Can you please put this in your next round of changes? Possibly check to see if “force SSL” is enabled or check to see if the site is “HTTPS” then use the google secure links?

    Your work is much appreciated!

    Thanks!

  10. first of all – i love you plugin!! it’s such a time and life savior!

    only 1 question i wanna ask:
    how do i use the file field in that plugin?
    becoz when i do that – it doesn’t save the picture i upload into that field into the field value.
    i do upload a picture – but it’s not connected to the meta_key.

    what do i need to do?
    thanks!

  11. Hi,

    Thanks for creating such a wonderful plugin.

    I have created group (repeated) called site links and it has Title & URL fields. And in the template file I used the following code:

    $site_links1 = simple_fields_get_post_group_values(get_the_id(), “Site Links”, true, 2);
    print_r($site_links1);
    foreach ($site_links1 as $key => $val) {
    echo “$key“;
    }

    But I get the following output:

    Array
    (
    [0] => Array
    (
    [Title] => Need Help?
    [URL] => http://someurl/help
    )

    [1] => Array
    (
    [Title] => Store
    [URL] => http://someurl/store
    )

    [2] => Array
    (
    [Title] => Specials
    [URL] => http://someurl/specials
    )

    [3] => Array
    (
    [Title] => Stars
    [URL] => http://someurl/stars
    )

    [4] => Array
    (
    [Title] => Drive
    [URL] => http://someurl/drives
    )

    [5] => Array
    (
    [Title] => Toys
    [URL] => http://someurl/toys
    )

    [6] => Array
    (
    [Title] => Video on Demand
    [URL] => http://someurl/vod
    )

    [7] => Array
    (
    [Title] => DVD’s
    [URL] => http://someurl/dvds
    )

    )

    01234567

    Any help will be highly appreciated.

  12. I need to do the same thing as Alok, I want a list of sources or credits at the end of my posts. Usually one, but could be more. Should have two fields, a name, and a URL, and I’ll need to wrap each name with each URL. Can you give a working example of this?

  13. Hi,

    I’m currently using your plugin and I love it but I’m stuck at a certain point.

    I made a field with type: file but how do I call the URL to an attachment so I can use it in my code?

    Currently

    $selected_value = simple_fields_get_post_value(get_the_id(), “imageurl”, true);

    gives “47” as a result. (47 being the id of attachment, but I need the URL to the attachment here)

    Thanks in advance!

    Yves

  14. Hi Joe,

    Did you get any work around for this? If yes, then please do let me know.

    BTW, I found one plugin (Post links)which could be of interest to you and I am also using it for the time being until I find a solution to the above issue. It allows you to add link along with title & description. You can add as many as you want and then display it using the shortcode or template tag.

    Although it very much solves the purpose but I still prefer to have only one plugin to play around with the fields instead of having different plugins.

    Regards,

    Alok

  15. Ok, once again for beginners. Let’s think of a REALLY EASY
    case, the very principle so to say. I’ve got one custom field. It
    is a text. The key is “client”. I will write the name of the client
    in there: John Doe. So, how do I call this field in my post? What
    am I to write in the single.php-template? This one finally worked
    for me: This shows the line: Name of the client: John Doe.

  16. Oh man, it’s complicated to explain something clearly ;o) I
    misspelled something in my code-snippet (a strange german word
    appeared). Here it is again, hopefully without any confusing stuff:
    $client = get_post_meta(get_the_id(), “client”, true); echo “Name
    of the client: $client”; This shows thel ine: Name of the client:
    John Doe. (My custom field is a text, the key is “client” and I’ve
    written the value “John Doe” in it.)

    • Thanks a lot for your example Kirsten! I will try to add some more simple examples to the tutorials page too.

      And…sorry about the comment system trashing your code. It’s not the first time it happens. I should really fix that… :/

    • What should I use in the case that the field type is a drop down?

      When I use the get_the_id for a drop down, it returns the drop down ID.. not the value of the dropdown. so..

      get_post_meta(get_the_id()

      returns something like:
      Maximum Age: dropdown_num_2

      I am thinking I should use something like:

      get_post_meta(get_the_value()

      but this does not work.. what is the correct method for different field types?
      Thanks.

  17. Hi Pär,

    I will very much appreciate if you can tell me that what code I would use to pull the data from repeatable fields and then format them as a hyperlink appearing on each link.

    I would like to pull the information from the Title & URL fields.

    Thanks in advance.

  18. After googleling I found a solution to output repeatable groups.
    In my example I have a video gallery where I have too values in my Video Gallery group, Video Name and Video URL.

    Output repeatable groups:

    if(have_posts()): while(have_posts()): the_post();

    $selected_values = simple_fields_get_post_group_values(get_the_id(), “Video Gallery”, false,2);

    foreach($selected_values as $value){

    print”$value[1]”;
    print”$value[2]”;
    }

    endwhile;
    endif;

  19. Just wanna let you know that this plugin is a beautiful step in direction wp->cms.
    Irreplaceable is the ‘repeatable’-feature with drag n’drop.
    Just love. Thanks so much for your effort !!!

  20. Hi

    I´m stuck, and a poor php programmer 🙂

    In my project I have made at couple of “Simple fields” and everything is working as a charm, but this I got stuck with. I have a text field where I want to put a url and it´s an optional text field. If I write an url I want WP to add that url to the page and the link will be an image. If I don´t write anything I want WP to ignore that line of code. Hope you understand.

    I have found this line of code who is exactly what I´m looking for, the problem is that I dont know how to adopt it to my case 🙂 How do I put Simple fields into this…

    <a class="action" href="”> →

    Thanks for a brilliant plugin!

  21. Hi There,
    Thanks for the great plugin – finally getting somewhere after playing with many other CPT plugins !

    In the docs you say this:

    Method 1
    Simple fields has it’s own function called simple_fields_get_post_value. It accepts three arguments: the id of the post we want to get the values for, the name or the id of the field that we wan’t to get the selected value from, and finally a boolean determin if the function should return all just the first value (useful if you have a field group with just one value) or all values for a field as an array (useful if you have a field group that is repeatable).

    But I see this example has 4 arguments !
    $slider = simple_fields_get_post_group_values($sliderID, “Homepage slide”, false, 2);

    Could you explain and update the documentation ?
    TIA, Dave

  22. Hello i have a question.
    I’m woking on a site now with a simple fields search but have no clue how to write the code for my search.

    I have 1 field on my posts with a drop down menu (3 alternatives atm)
    Then i have 1 checkbox

    How do i do if i want to be able to select 1 or more categories in the search, select the checknox or not and ramdomly select 1-10 posts (a number that the user choose)

Leave a Reply to Christian Cancel reply