mardi 26 mai 2015

Wordpress: Creating a dynamic checkbox group using a post loop in functions.php

Thank you for taking the time to read this, I'll explain best I can. Any help is appreciated.

I have a checkbox group available for me to use for each of my Wordpress posts. It allows me to tick/check which people are featured in the current post. I achieved this by adding this code to my functions.php file:

function add_custom_meta_box() {
add_meta_box(
    'custom_meta_box',
    'Featured People',
    'show_custom_meta_box',
    'post',
    'side',
    'core'
);}

add_action('add_meta_boxes', 'add_custom_meta_box');

// Field Array

$prefix = 'custom_';
$custom_meta_fields = array(

array (
'label' => '',
'desc'  => '',
'id'    => $prefix.'checkbox_group',
'type'  => 'checkbox_group',
'options' => array (
    '1' => array (
        'label' => 'Person One',
        'value' => 'personone'
    ),
    '2' => array (
        'label' => 'Person Two',
        'value' => 'persontwo'
    ),
    '3' => array (
        'label' => 'Person Three',
        'value' => 'personthree'
    ),  
    '4' => array (
        'label' => 'Person Four',
        'value' => 'personfour'

    // Add More People Here

    ),
)
)
);

This works all fine, however, I'm sure you'll agree that it would be very tedious to keep adding people each time there's a new person.

So, in an attempt to make this checkbox group more dynamic, I created a new custom post type that allows me to add the information for each person the same way you would add the content for a normal post in wp-admin. The only problem is I can't figure out how to loop through this custom post type in functions.php.

This is what I want to do:

array (
   'label' => '',
   'desc'  => '',
   'id'    => $prefix.'checkbox_group',
   'type'  => 'checkbox_group',
   'options' => array (

$args = array( 
   'post_type' => 'featured-people',        //LOOP THROUGH THIS POST TYPE
   'posts_per_page' => -1 );
$query = new WP_Query( $args );

while ($query->have_posts()) : $query->the_post();

      'the_title();' => array (             //FOR EACH, DO THIS
          'label' => 'the_title();',  
          'value' => 'the_value();'   
      ),

endwhile

I'm hoping to make this post type populate the checkbox group, and each time a new person is added, the checkbox group will update to include them as an option.

(I then have to figure out how to display the information on single.php, but one thing at a time).

Any help would be greatly appriciated. Thank you!




Aucun commentaire:

Enregistrer un commentaire