刚刚创建了此代码,这是将herky-jerk javascript链接到表单字段的完整解决方法。由于复选框的值与$ _POST一起在提交时传递,因此您只需在add_image_attachment_fields_to_save过滤器中获取它们并设置post对象的条款即可。
function register_custom_taxonomies() {
$labels = array(
'name' => _x( 'Image Formats', 'taxonomy general name' ),
'singular_name' => _x( 'Image Format', 'taxonomy singular name' ),
'search_items' => __( 'Search Formats' ),
'all_items' => __( 'All Formats' ),
'parent_item' => __( 'Parent Format' ),
'parent_item_colon' => __( 'Parent Format:' ),
'edit_item' => __( 'Edit Format' ),
'update_item' => __( 'Update Format' ),
'add_new_item' => __( 'Add New Format' ),
'new_item_name' => __( 'New Format Name' ),
'menu_name' => __( 'Image Format' )
);
$capabilities = array(
'manage_terms' => 'nobody',
'edit_terms' => 'nobody',
'delete_terms' => 'nobody'
);
$args = array(
'public' => false,
'hierarchical' => true,
'labels' => $labels,
'capabilities' => $capabilities,
'show_ui' => false,
'query_var' => 'image-format',
'rewrite' => false
);
register_taxonomy('image-format', array('attachment'), $args);
}
add_action( 'init', 'register_custom_taxonomies', 1);
function add_media_categories($fields, $post) {
$categories = get_categories(array('taxonomy' => 'image-format', 'hide_empty' => 0));
$post_categories = wp_get_object_terms($post->ID, 'image-format', array('fields' => 'ids'));
$all_cats .= '<ul id="media-categories-list" style="width:500px;">';
foreach ($categories as $category) {
if (in_array($category->term_id, $post_categories)) {
$checked = ' checked="checked"';
} else {
$checked = '';
}
$option = '<li style="width:240px;float:left;"><input type="checkbox" value="'.$category->category_nicename.'" id="'.$post->ID.'-'.$category->category_nicename.'" name="'.$post->ID.'-'.$category->category_nicename.'"'.$checked.'> ';
$option .= '<label for="'.$post->ID.'-'.$category->category_nicename.'">'.$category->cat_name.'</label>';
$option .= '</li>';
$all_cats .= $option;
}
$all_cats .= '</ul>';
$categories = array('all_categories' => array (
'label' => __('Image Formats'),
'input' => 'html',
'html' => $all_cats
));
return array_merge($fields, $categories);
}
add_filter('attachment_fields_to_edit', 'add_media_categories', null, 2);
function add_image_attachment_fields_to_save($post, $attachment) {
$categories = get_categories(array('taxonomy' => 'image-format', 'hide_empty' => 0));
$terms = array();
foreach($categories as $category) {
if (isset($_POST[$post['ID'].'-'.$category->category_nicename])) {
$terms[] = $_POST[$post['ID'].'-'.$category->category_nicename];
}
}
wp_set_object_terms( $post['ID'], $terms, 'image-format' );
return $post;
}
add_filter('attachment_fields_to_save', 'add_image_attachment_fields_to_save', null , 2);
(请注意,我使用的是自定义分类法,而不是类别,因此您必须更改$ categories数组以匹配设置复选框时使用的相同数组)
沙巴姆,sha。请享用。