Simple Fields tutorial, part 2: getting the values

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

 

 

// To get values from a field simple use the function simple_fields_value() like this:
$field_value = simple_fields_value("slug_of_field");

// You can even pass meny slugs to retrieve array of values:
$field_value = simple_fields_value("slug_of_field1, another_slug, and_a_third_slug");

 

79 thoughts on “Simple Fields tutorial, part 2: getting the values

  1. vinayak

    Hi am vinayak
    i am new to this wordpress and i successfully installed simple field plugin to add one drop-down list where can i select one value and print that value along with the article here is my code
    surl is name i given in simple field that is drop-down list
    <?php
    // Get the saved value for a field
    //using simple field get_post_meta( get_the_ID(), 'selecturl', true);
    $site_url = simple_fields_value('surl');
    echo 'Site URL: ‘ . $site_url . ”;
    ?>

    am getting output like thisbelow
    Site URL: dropdown_num_2

    please can anybody help me out

  2. andrei

    hello, i don’t know if is possible but i want to do this:

    i have a field for author name and i want to find a solution to display all posts from this author on click in a special page.

    thanx!
    andrei

  3. dillon

    Is it possible to return all custom fields from all groups on the page?

    as i need to do a foreach on the groups.

    Thanks

  4. Karolina Nilsson

    I have three checkboxes Grön Röd and Svart. Each one is an icon that I want to display if the checkbox is actually checked. But with this [code] $selected_value = simple_fields_get_post_value(get_the_id(), “Svårighetsgrad”, true);
    echo ”; [/code] I only get one of them or if I cody this code and get the three different images I get all Three of them even though only one checkbox is checked. How to check if the checkbox is checked and then the the right icon?

    I want to be able to pick all of them in one post. So no ifs?! 😉

    Anyone?

  5. piotrbalinski

    Hello, thanks for an innovative plugin. I try to display a few photos in my theme, and use a code:
    $val) {
    echo “$val”;
    }?>
    But I get:
    Array
    (
    [0] => Array
    (
    [zdjęcie] => 28
    [tytuł] => od frontu
    )

    [1] => Array
    (
    [zdjęcie] => 26
    [tytuł] => widok z balkonu
    )

    )
    ArrayArray

    what should I do to obtain a url of a file?Thank you, Piotr

  6. david parker

    Having trouble getting values from dropdown list. using this code

    simple_fields_value(‘saeason_start’);

    season_start is the name of the dropdown. Using the code above, when the first item on the dropdown is selected I get ‘dropdown_num_2’ as the output instead of the value of the dropdown option. What’s the correct way to get the value from the dropdown selector?

    1. Pär Thernström Post author

      Try this:
      simple_fields_value(‘saeason_start’, null, “enable_extended_return_values=1”);
      it will give you a very useful array, and among all values are the name of the selected dropdown. use print_r($your_variable) to show all values…

  7. Caroline Elisa

    Hi there, great plugin thanks!

    I’ve just been struggling to display images pulled from a repeatable file field.

    I’m trying this, am I close?!:

    $drinksmenu = simple_fields_values(“drink_menu”);
    foreach ($drinksmenu as $drinkmenu) {
    $image_url = wp_get_attachment_image_src( $drinkmenu );
    echo ”;
    }

        1. Caroline Elisa

          A lot! Starting with the following of which [“url”]=>
          string(79) is the value I’m after:

          array(9) {
          [“id”]=>
          int(26)
          [“is_image”]=>
          bool(true)
          [“url”]=>
          string(79) “http://the3crowns.co.uk/wordpress/wp-content/uploads/Three-Crowns-Menu-v6_4.jpg”
          [“mime”]=>
          string(10) “image/jpeg”
          [“link”]=>
          array(4) {
          [“full”]=>
          string(304)

          1. Pär Thernström Post author

            ah, you have all you need there
            this should do the trick:
            to output the url to the image just write:

            echo $drinkmenu[“image”][“thumbnail”];

            to output the thumnail version of the image

  8. Harry

    First of all: great plugin, cheer for you!

    Now to business; i got the following code:

    ‘5’, ‘category’ => ‘2’ );
    $recent_posts = wp_get_recent_posts( $args );
    foreach( $recent_posts as $recent ){
    echo ‘‘ . $recent[“post_title”].’ ‘;
    }
    ?>

    Each post has 3 checkboxes (playstation3, xbox360, pc). So if a post has PC checked, then i need to return the value. How do i return the value of these checkboxes?

    PS. multi values should be possible. So a game in Xbox360 and PC.

    Sorry for the bad englisch!

    1. Jose

      Hi Nando,

      Could you please tell the community about your brillant alternative to it? Thanks a lot you all mighty coding genius

  9. Clay

    This is driving me crazy… I’ve spent 2 hours trying to figure this out.

    I have a custom post type called “Portfolio”.

    All I want to do is add 3 fields (all simple text fields)…

    1.) Web Address (this one actually needs to be a link)
    2.) Project Scope
    3.) Work Completed

    I need this to show up in the post on all “portfolio” custom posts.

    I added the code you guys suggested in method 2 to single-portfolio.php. It shows up but it did so above the header. I need it to show up in the post content.

    I have tried creating a function (to the best of my ability) and then hooking it to the hook that I thought would put it in the correct place but I can’t make it work. Can anyone help me?

    It’s drive me nuts that I always see “just add this code…” but nobody says where to add the code (not just on your site but on other sites relating to other stuff as well).

    Admittedly, I am not much of a PHP guru at all…Any help would be appreciated. Please email me if possible. Thanks!

    1. Clay

      OK…. figure it out…. I added this to my single-portfolio.php

      /** Add Simple Fields */
      function simple_fields() {
      $selected_value = simple_fields_get_post_value(get_the_id(), array(1, 3), true);
      echo “Project Scope: $selected_value”;}

      add_action( ‘genesis_post_content’, ‘simple_fields’ );

      NOW…. I need to figure out how to give each field a class. I would like to give “Project Scope” an H3 tag. Anybody know how?

      1. Clay

        Well… figure that out too…. on a guess no less.

        (sorry to bother all of you with this stuff… just figure someone else might be trying to figure out the same thing)

        /** Add Simple Fields */
        function simple_fields() {
        $selected_value = simple_fields_get_post_value(get_the_id(), array(1, 3), true);
        echo “Project Scope: $selected_value”;}

        add_action( ‘genesis_post_content’, ‘simple_fields’ );

        1. Clay

          Forgot to mention that I am using the genesis framework. that’s why I have the hooks I have. Make sure you know what hooks you need. if you’re not using Genesis, you’ll need different hooks.

          1. Clay

            ALSO… messes up earlier… to add H3 tags to the function….

            /** Add Simple Fields */
            function simple_fields() {
            $selected_value = simple_fields_get_post_value(get_the_id(), array(1, 3), true);
            echo “Project Scope: $selected_value”;}

            add_action( ‘genesis_post_content’, ‘simple_fields’ );

          2. Clay

            EDIT…. the comment section here removes my H3 Tags… You need to just add “h” tags around the things you want them added to.

  10. Pingback: 深度利用Wordpress的文章自定义段—Simple Field插件推荐 – 费克熊猫

  11. Niklas

    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)

  12. Dave Porter

    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

  13. ricwes

    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!

  14. norty

    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 !!!

  15. Luis

    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;

  16. Alok Sharma

    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.

  17. Kirsten

    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.)

    1. Pär Post author

      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… :/

    2. Chad

      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.

  18. Kirsten

    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.

  19. Alok

    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

  20. Yves

    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

  21. Joe

    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?

      1. Dennis

        $site_links1 = simple_fields_get_post_group_values(get_the_id(), ”Site Links”, true, 2);
        foreach ($site_links1 as $key => $val) {
        echo ”<a href=’”.$val[“URL”].”’>”.$val[“name”]”.</a>”;
        }

  22. Alok

    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.

  23. ilan

    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!

  24. Aaron

    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!

  25. Mac

    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

  26. Tobias

    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!

  27. Christian

    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

    1. David

      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. 🙂

  28. Staffan Estberg

    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?

  29. Johan

    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:wampwwwreview-itwp-contentpluginssimple-fieldsfunctions_post.php on line 675
    Warning: array_merge() [function.array-merge]: Argument #2 is not an array in C:wampwwwreview-itwp-contentpluginssimple-fieldsfunctions_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?

    1. Pär Post author

      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?

      1. Johan

        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?

        1. Pär Post author

          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!

          1. Johan

            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

          2. Johan

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

          3. Pär Post author

            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 🙁

    2. Patrik E

      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”]]);

  30. Vero

    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)

  31. Lynne

    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

Leave a Reply