Create Meta boxes dynamically

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 fieldTrack 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:

After saving

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.

$299 Affordable Web Design WordPress

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Create Meta boxes dynamically

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.