Answers:
所以你的意思是这样的吗?
当您点击添加曲目时,它变为:
如果这是您的意思,那么通过创建一个具有简单jquery功能的metabox来完成操作,以在其中添加和删除字段,并将数据保存为单个元行中数据的数组,请执行以下操作:
add_action( 'add_meta_boxes', 'dynamic_add_custom_box' );
/* Do something with the data entered */
add_action( 'save_post', 'dynamic_save_postdata' );
/* 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 Tracks', 'myplugin_textdomain' ),
'dynamic_inner_custom_box',
'post');
}
/* 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 array
$songs = get_post_meta($post->ID,'songs',false);
$c = 0;
if ( count( $songs ) > 0 ) {
foreach( $songs as $track ) {
if ( isset( $track['title'] ) || isset( $track['track'] ) ) {
printf( '<p>Song Title <input type="text" name="songs[%1$s][title]" value="%2$s" /> -- Track number : <input type="text" name="songs[%1$s][track]" value="%3$s" /><span class="remove">%4$s</span></p>', $c, $track['title'], $track['track'], __( 'Remove Track' ) );
$c = $c +1;
}
}
}
?>
<span id="here"></span>
<span class="add"><?php _e('Add Tracks'); ?></span>
<script>
var $ =jQuery.noConflict();
$(document).ready(function() {
var count = <?php echo $c; ?>;
$(".add").click(function() {
count = count + 1;
$('#here').append('<p> Song Title <input type="text" name="songs['+count+'][title]" value="" /> -- Track number : <input type="text" name="songs['+count+'][track]" value="" /><span class="remove">Remove Track</span></p>' );
return false;
});
// The live() method was deprecated in jQuery version 1.7, and removed in version 1.9. Use the on() method instead. We can use .on
$(".remove").live('click', function() {
$(this).parent().remove();
});
});
</script>
</div><?php
}
/* 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['songs'];
update_post_meta($post_id,'songs',$songs);
}
var_dump($songs);
if (count($songs) > 0){
为if(is_array($songs)){
这是通过自定义字段完成的,但您绝不要使用任何允许用户添加创建或删除元框的方法。这些直接写入数据库,因此如果您为用户提供这种控制,则可能为您的站点带来很多问题。为您创建它们可能需要的最大数量的自定义字段,并让它们在不需要的地方留一些空白是非常安全的。
这也是插件领域。功能文件是特定于主题的,而插件是适用于适用于网站内容的功能的,特别是如果您希望无论使用哪种主题都可以使用该内容。
一些建议: