admin管理员组

文章数量:1122846

I followed and created a meta box using all code from this question here:

Create more Meta Boxes as needed

Basically only two fields are created when you click on Add track button:

Song title field - Track number field

But I need something like that:

Add album name button - add a field for a album name;
Add track number button - add a field for track number;

This is my code right now:

add_action( 'add_meta_boxes', array( $this, 'dynamic_add_custom_box' ) );

/* Do something with the data entered */
add_action( 'save_post', array( $this, 'dynamic_save_postdata' ) );

Second block:

/* Adds a box to the main column on the Post and Page edit screens */     
function dynamic_add_custom_box() {
  add_meta_box(
      'dynamic_sectionid',
      __( 'My Albums', 'myplugin_textdomain' ),
      array( $this,'dynamic_inner_custom_box'),
      'post',
      'normal',
    'high');
}

Third block:

/* Prints the box content */
function dynamic_inner_custom_box() {
global $post;
// Use nonce for verification
wp_nonce_field( plugin_basename( __FILE__ ), 'dynamicMeta_noncename' );
?>
<div id="meta_inner">
<?php

//get the saved meta as an arry
$albums = get_post_meta( $post->ID, 'album', true );

$c = 0;
if ( count( $albums ) > 0 ) {
    foreach( $albums as $album ) {
        if ( isset( $album['title'] ) || isset( $album['track'] ) ) {
            printf( '<p>Album name <input type="text" name="album[%1$s][title]" value="%2$s" /> -- Track number : <input type="text" name="album[%1$s][track]" value="%3$s" /><span class="removealbum">%4$s</span></p>', $c, $album['title'], $album['track'], __( 'Remove Album' ) );
            $c = $c +1;
        }
    }
}

?>
<span id="here"></span>
<span class="button addalbum"><?php _e('Add Album'); ?></span>
<span class="button addtracks"><?php _e('Add Tracks'); ?></span>
<script>
var $ =jQuery.noConflict();
$(document).ready(function() {
var count = <?php echo $c; ?>;
    $(".addalbum").click(function() {
        count = count + 1;

        $('#here').append('<p> Album name <input type="text" name="album['+count+'][title]" value="" /><span class="removealbum">Remove Album</span></p>' );
        return false;
    });
    $(".addtracks").click(function() {
        count = count + 1;

        $('#here').append('<p> Track number : <input type="text" name="album['+count+'][track]" value="" /><span class="removetrack">Remove Track</span></p>' );
        return false;
    });
$(".removealbum").live('click', function() {
        $(this).parent().remove();
    });
$(".removetrack").live('click', function() {
        $(this).parent().remove();
    });
});
   </script>
</div>

<?php }

Last block:

/* When the post is saved, saves our custom data */
function dynamic_save_postdata( $post_id ) {
// verify if this is an auto save routine.
// If it is our form has not been submitted, so we dont want to do anything
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
    return;

// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !isset( $_POST['dynamicMeta_noncename'] ) )
    return;

if ( !wp_verify_nonce( $_POST['dynamicMeta_noncename'], plugin_basename( __FILE__ ) ) )
    return;

// OK, we're authenticated: we need to find and save the data

$songs = $_POST['album'];

update_post_meta( $post_id, 'album', $songs );
}

Before save anything:

album    NULL

Meta key & meta value are OK;

After save something:

Meta value - They are in a different group of array. It's not possible to relate which album relates with each track number.

album 'a:2:{i:2;a:1:{s:5:"title";s:22:"Anjunabeats Volume Six";}i:3;a:1:{s:5:"track";s:1:"5";}}'

What I need is this:

Album[0]
Track number [0]
Track number [1]

Album[1]
Track number [0]
Track number [1]
Track number [2]

Album[2]
Track number [0]

I tried so many things, but I am stuck here :(

Any idea would be helpful.

I followed and created a meta box using all code from this question here:

Create more Meta Boxes as needed

Basically only two fields are created when you click on Add track button:

Song title field - Track number field

But I need something like that:

Add album name button - add a field for a album name;
Add track number button - add a field for track number;

This is my code right now:

add_action( 'add_meta_boxes', array( $this, 'dynamic_add_custom_box' ) );

/* Do something with the data entered */
add_action( 'save_post', array( $this, 'dynamic_save_postdata' ) );

Second block:

/* Adds a box to the main column on the Post and Page edit screens */     
function dynamic_add_custom_box() {
  add_meta_box(
      'dynamic_sectionid',
      __( 'My Albums', 'myplugin_textdomain' ),
      array( $this,'dynamic_inner_custom_box'),
      'post',
      'normal',
    'high');
}

Third block:

/* Prints the box content */
function dynamic_inner_custom_box() {
global $post;
// Use nonce for verification
wp_nonce_field( plugin_basename( __FILE__ ), 'dynamicMeta_noncename' );
?>
<div id="meta_inner">
<?php

//get the saved meta as an arry
$albums = get_post_meta( $post->ID, 'album', true );

$c = 0;
if ( count( $albums ) > 0 ) {
    foreach( $albums as $album ) {
        if ( isset( $album['title'] ) || isset( $album['track'] ) ) {
            printf( '<p>Album name <input type="text" name="album[%1$s][title]" value="%2$s" /> -- Track number : <input type="text" name="album[%1$s][track]" value="%3$s" /><span class="removealbum">%4$s</span></p>', $c, $album['title'], $album['track'], __( 'Remove Album' ) );
            $c = $c +1;
        }
    }
}

?>
<span id="here"></span>
<span class="button addalbum"><?php _e('Add Album'); ?></span>
<span class="button addtracks"><?php _e('Add Tracks'); ?></span>
<script>
var $ =jQuery.noConflict();
$(document).ready(function() {
var count = <?php echo $c; ?>;
    $(".addalbum").click(function() {
        count = count + 1;

        $('#here').append('<p> Album name <input type="text" name="album['+count+'][title]" value="" /><span class="removealbum">Remove Album</span></p>' );
        return false;
    });
    $(".addtracks").click(function() {
        count = count + 1;

        $('#here').append('<p> Track number : <input type="text" name="album['+count+'][track]" value="" /><span class="removetrack">Remove Track</span></p>' );
        return false;
    });
$(".removealbum").live('click', function() {
        $(this).parent().remove();
    });
$(".removetrack").live('click', function() {
        $(this).parent().remove();
    });
});
   </script>
</div>

<?php }

Last block:

/* When the post is saved, saves our custom data */
function dynamic_save_postdata( $post_id ) {
// verify if this is an auto save routine.
// If it is our form has not been submitted, so we dont want to do anything
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
    return;

// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !isset( $_POST['dynamicMeta_noncename'] ) )
    return;

if ( !wp_verify_nonce( $_POST['dynamicMeta_noncename'], plugin_basename( __FILE__ ) ) )
    return;

// OK, we're authenticated: we need to find and save the data

$songs = $_POST['album'];

update_post_meta( $post_id, 'album', $songs );
}

Before save anything:

album    NULL

Meta key & meta value are OK;

After save something:

Meta value - They are in a different group of array. It's not possible to relate which album relates with each track number.

album 'a:2:{i:2;a:1:{s:5:"title";s:22:"Anjunabeats Volume Six";}i:3;a:1:{s:5:"track";s:1:"5";}}'

What I need is this:

Album[0]
Track number [0]
Track number [1]

Album[1]
Track number [0]
Track number [1]
Track number [2]

Album[2]
Track number [0]

I tried so many things, but I am stuck here :(

Any idea would be helpful.

Share Improve this question edited Apr 13, 2017 at 12:37 CommunityBot 1 asked Dec 30, 2016 at 15:16 David MedeirosDavid Medeiros 12 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

How about using a proper metabox framework for your project? I'm sure that`s not the single metabox you'll be using.

I recommend you https://metabox.io/meta-box/ - I used it on many of my projects and have features for dynamic fields as well.

Happy new year!

本文标签: custom fieldCreate Meta boxes dynamically