Viewing 4 reply threads
  • Author
    Posts
    • #7582
      daprela
      Participant

      I need to create a select option which has not a fixed number of options but they are calculated every time based on other conditions. Is that possible?

    • #7585
      Jason
      Keymaster

      Hi @deprela!

      Sure! It’s just normal PHP so you can set choices to be whatever you need. You can use get_posts, wp_get_post_terms, or any other function to get the values and then set them as the choices (where the key is the value stored in the database and the value is the label presented to the user). You can even use the piklist function to pluck the values from collections:

      piklist('field', array(
        'type'      => 'select',
        'field'     => 'related_post',
        'label'     => 'Related Post',
        'choices'   => piklist(get_posts(array(
          'post_type'   => 'post',
          'numberposts' => -1
        )), array('ID', 'post_title'))
      ));

      Hope this helps!

    • #7662
      Juan
      Participant

      Hi @Jason!

      is it posible to add a default first choice? something like: “Select one post…”

      thanks!

      
        piklist('field', array(
        'type'      => 'select',
        'field'     => 'staff_member',
        'label'     => 'Add Staff Members',
        'columns'   => 12,
        'add_more'  => true,
        'choices'   => piklist(get_posts(array(
        	'none' => 'Select one post…' ,
          'post_type'   => 'staff',
          'numberposts' => -1
        )), array('ID', 'post_title'))
      ));
    • #7664
      Jason
      Keymaster

      Hi @Juan!

      It sure is! Just like this:

      piklist('field', array(
        'type'      => 'select',
        'field'     => 'staff_member',
        'label'     => 'Add Staff Members',
        'columns'   => 12,
        'value'     => '',
        'add_more'  => true,
        'choices'   => array('' => 'Select one post...') + piklist(get_posts(array(
          'post_type'   => 'staff',
          'numberposts' => -1
        )), array('ID', 'post_title'))
      ));

      Notice two things here: First, I added a 'value' => '' line that tells Piklist what the default value of the field is when there’s no value saved, yet. Second, I added the array('' => 'Select one post...') + line. This adds an option to the beginning of the choices with a stored value of nothing, while displaying ‘Select one post…’

      Hope this helps! 🙂

    • #7665
      Juan
      Participant

      thanks Jason!

Viewing 4 reply threads
  • The topic ‘Creating dynamic select’ is closed to new replies.