WordPress get metabox info for selected custom post type

I have a form, created as a plugin in wordpress. In the form is a drop down select menu that is populated with all entries from a custom post type called ‘singers’.

i.e. “singer 1, singer 2, singer 3”

Read More

In this custom post type, each singer has meta box info, the info I’m interested in is ‘singer_gender’. When a singer is selected, I want to pass a variable into a hidden field on that form with either “male” or “female”

So, for example, if Singer 1 is selected, and is male, my form would have the following hidden field:

<input type="hidden" name="singer_gender" id="singer_gender" value="<?php echo singer_gender; ?>" />

Is there a way to make this happen?

Related posts

2 comments

  1. You would use get_post_meta to retrieve values entered in a meta box.

    If singer_gender is the meta box key, your code might look like this:

    <?php
      global $post;
      $single_gender = get_post_meta($post->ID, 'singer_gender', true);
    ?>
    
    <input type="hidden" name="singer_gender" id="singer_gender" value="<?php echo $singer_gender; ?>" />
    
  2. You could store the gender inside a data value on the options of the select.

    Like this:

    $('#person').change(function(){
    	var gender = $(this).find('option:checked').attr('data-gender');
        $('#gender_hidden').val(gender);
        $('#gender').val(gender);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form>
        <input type="hidden" id="gender_hidden" />
        <input type="text" id="gender" />
        <select id="person" onchange="change(this);">
            <option value="Person_1" data-gender="male">Person 1</option>
            <option value="Person_2" data-gender="female">Person 2</option>
            <option value="Person_3" data-gender="male">Person 3</option>
        </select>
    </form>

    To generate the HTML for that use get_post_meta

    <?php
    $args = array('post_type'=>'people');
    
    $people = WP_Query($args);
    if ($people->have_posts()) ?>
        <input id="gender" name="gender" />
        <select name="person">
            <?php while ($people->have_posts()){ $people->the_post();
                global $post;
                $name = get_the_title();
                $slug = $post->post_name;
                $gender = get_post_meta($post->ID, 'gender', true);
            ?>
            <option data-gender="<?php echo $gender; ?>" value="<?php echo $slug; ?>"><?php echo $name; ?></option>
            <?php } ?>
        </select>
    <?php }
    

Comments are closed.