0
votes

I have a wordpress custom post type with a custom meta box. With the meta box I can save 3 checkboxes. But how do I get the data from those checkboxes in my theme?

This is my function

function social_services( $post )
{
    // Get post meta value using the key from our save function in the second paramater.
    $custom = get_post_meta($post->ID, '_social_services', true);

    ?>
        <input type="checkbox" id="social_services_soundcloud" name="social_services[]" value="soundcloud" <?php echo (in_array('soundcloud', $custom)) ? 'checked="checked"' : ''; ?>>
        <label for="social_services_soundcloud"></label>Soundcloud<br>

        <input type="checkbox" id="social_services_facebook" name="social_services[]" value="facebook" <?php echo (in_array('facebook', $custom)) ? 'checked="checked"' : ''; ?>>
        <label for="social_services_facebook"></label>Facebook<br>

        <input type="checkbox" id="social_services_twitter" name="social_services[]" value="twitter" <?php echo (in_array('twitter', $custom)) ? 'checked="checked"' : ''; ?>>
        <label for="social_services_twitter"></label>Twitter<br>
    <?php
}

function save_extra_fields(){
  global $post;

    if(isset( $_POST['social_services'] ))
    {
        $custom = $_POST['social_services'];
        $old_meta = get_post_meta($post->ID, '_social_services', true);
        // Update post meta
        if(!empty($old_meta)){
            update_post_meta($post->ID, '_social_services', $custom);
        } else {
            add_post_meta($post->ID, '_social_services', $custom, true);
        }
    }
  // update_post_meta($post->ID, "producers", $_POST["producers"]);
}
add_action( 'save_post', 'save_extra_fields' );

EDIT: I fixed it with this:

if (in_array('soundcloud', get_post_meta($post->ID, '_social_services', true)) == true) {
  // Show the content here
  echo "soundcloud";
}
1
Are the meta values saving to the database fine? You can access them individually with: <?php $meta_values = get_post_meta( $post_id, $key, $single ); ?>rnevius
It's saving fine, I also see the checkbox is still checked when I switch pages.Steven de Jong
Why can't you write the conditional using the $custom variable that holds the value of the meta key? Something like: if ($custom) { // Do Something }rnevius
I fixed it with this: if (in_array('soundcloud', get_post_meta($post->ID, '_social_services', true)) == true) { // Show the content here echo "soundcloud"; }Steven de Jong
You can drop the end == true to simplify things. Add your find as an answer, rather than an edit! I'll upvote. Good problem solving.rnevius

1 Answers

1
votes

I fixed it with this:

if (in_array('soundcloud', get_post_meta($post->ID, '_social_services', true)) == true) {
  // Show the content here
  echo "soundcloud";
}