Viewing 1 reply thread
  • Author
    Posts
    • #10869
      guit4eva
      Participant

      Hey everyone 🙂

      How would I get the value of a select field? In the following:

      piklist('field', array(
          'type' => 'select',
          'field' => 'establishment_no_bedrooms',
          'label' => 'Number of Bedrooms',
          'choices' => array(
              '1_bedroom' => '1',
              '2_bedroom' => '2',
              '3_bedroom' => '3',
              '4_bedroom' => '4',
              '5_bedroom' => '5',
              '6_bedroom' => '6',
              '7_bedroom' => '7+',
          ),
      ));

      Using:
      <?php echo get_post_meta($post->ID, 'establishment_no_bedrooms', true);?>
      returns the key:
      1_bedroom

      How can I get the value instead?

      Thanks in advance!

    • #10875
      Steve
      Keymaster

      @guit4eva– Since Piklist is file driven, and not database driven, you can’t really get the values by default. However, we’ve run into this in the past as well for our clients, and here are two solutions:

      1) Name the keys the values you want to display:

      piklist('field', array(
          'type' => 'select',
          'field' => 'establishment_no_bedrooms',
          'label' => 'Number of Bedrooms',
          'choices' => array(
              '1' => '1',
              '2' => '2',
              '3' => '3',
              '4' => '4',
              '5' => '5',
              '6' => '6',
              '7+' => '7+',
          ),
      ));

      Obviously, that’s the easiest.

      2. List your choices in a separate function.

      One of the things that makes Piklist so great, is that you can use functions to generate field options and reuse them. In another file (not your Piklist parts file), like functions.php do something like:

      function establishment_no_bedrooms_list($choice = null) {
      
        $choices = array (
          '1_bedroom' => '1',
          '2_bedroom' => '2',
          '3_bedroom' => '3',
          '4_bedroom' => '4',
          '5_bedroom' => '5',
          '6_bedroom' => '6',
          '7_bedroom' => '7+',
        );
      
       If ($choice === null {
      
        return $choices;
      
      } else {
      
        return $choices[$choice];
      
      }

      That function says, if you don’t pass a choice return the choices. If you do pass a choice, return the value.

      Then in your Piklist parts file reference the function.

      piklist('field', array(
          'type' => 'select',
          'field' => 'establishment_no_bedrooms',
          'label' => 'Number of Bedrooms',
          'choices' => establishment_no_bedrooms_list()
          ),
      ));

      and in your theme:
      echo establishment_no_bedrooms_list( get_post_meta($post->ID, 'establishment_no_bedrooms', true ) );

      IMPORTANT: This is untested and may require some tweaking.

Viewing 1 reply thread
  • You must be logged in to reply to this topic.