say you have 10 group names, labeled ‘$group_1’, ‘$group_2’, etc. and you want to display each of them. a quick way to do that is to use dynamic variables (aka variable variables)
1 | for ( $i = 1; $i < 11; $i ++) { |
that’s a super simple implementation. i needed to use it for a recent project — it was pretty intense to figure out the logic, but this is what i came up with
i needed to add some custom post meta fields to the wordpress admin for 13 groups (simplified, adding a WIZZY editor for the editor to add bios for each group), but didn’t want to write 13 versions of pretty much the same code, save for a incrementing variable in the name
01 | for ( $i = 1; $i < 14; $i ++) { |
02 | $group_bio = 'group_' . $i . '_bio' ; |
03 | $ $group_bio = get_post_meta( $object ->ID, '_group_' . $i . '_bio' , true); |
08 | <label for = "'.$group_bio.'" >GROUP Bio</label> |
09 | '.wp_editor( $$group_bio, $group_bio, array(false, true, $group_bio, 4) ).' |
one of the toughest parts to wrap my head around in the beginning was the $$group_bio variable. take it one line at a time:
$group_bio = 'group_' . $i . '_bio';
for example, the first iteration, that $group_bio
variable will be ‘group_1_bio
‘
the next line will then make ‘group_1_bio
‘ into a variable: $group_1_bio
, which will store the post_meta data stored in _group_1_bio
that snippet of code will make 13 of my WIZZY editors on the page — this keeps my functions.php leaner!
want to save the data and still keep your functions.php file clean?
this goes somewhere in your save_post
class:
01 | for ( $i =1; $i < 14; $i ++) { |
02 | $new_meta_value = ( isset( $_POST [ 'group_' . $i . '_bio' ] ) ? $_POST [ 'group_' . $i . '_bio' ] : '' ); |
03 | $meta_value = get_post_meta( $post_id , '_group_' . $i . '_bio' , true ); |
04 | if ( $new_meta_value && '' == $meta_value ) |
05 | add_post_meta( $post_id , '_group_' . $i . '_bio' , $new_meta_value , true ); |
06 | elseif ( $new_meta_value && $new_meta_value != $meta_value ) |
07 | update_post_meta( $post_id , '_group_' . $i . '_bio' , $new_meta_value ); |
08 | elseif ( '' == $new_meta_value && $meta_value ) |
09 | delete_post_meta( $post_id , '_group_' . $i . '_bio' , $meta_value ); |