我正在使用CMB2(https://github.com/CMB2/CMB2) 用于向帖子类型添加新元。
我正在尝试添加一个新的自定义元,其中包含按分类法分组的帖子列表,但我不知道如何保存它们。我想将meta保存为一个数组,如下所示:
array (
id => array (checked, new_title),
id2 => array (checked, new_title2)
)
自定义元的源代码:
// Enqueue accordion scripts.
add_action( \'admin_enqueue_scripts\', function($hook){
if (( \'post.php\' == $hook ) || ( \'post-new.php\' == $hook)) {
wp_enqueue_script( \'accordion\', \'/wp-admin/js/accordion.js\');
}
});
// Custom CMB2 field list_category_posts
add_action( \'cmb2_render_post_multicheck_by_category\', \'cmb2_render_post_multicheck_by_category\', 10, 5 );
function cmb2_render_post_multicheck_by_category ( $field, $value, $object_id, $object_type, $field_type ) {
// get post_type
if ($field->args[query_args][post_type])
if (post_type_exists($field->args[query_args][post_type]))
$type=$field->args[query_args][post_type];
else $type=get_post_type($object_id);
else $type=get_post_type($object_id);
// get taxonomy
if ($field->args[query_args][taxonomy])
if (taxonomy_exists($field->args[query_args][taxonomy]) && is_object_in_taxonomy($type, $field->args[query_args][taxonomy]))
$taxonomy=$field->args[query_args][taxonomy];
else $taxonomy=get_object_taxonomies($type)[0];
else $taxonomy=get_object_taxonomies($type)[0];
$posts_data = array();
$terms = get_terms($taxonomy);
foreach ($terms as $term) {
$posts = get_posts(array(
\'post_type\' => $type,
\'tax_query\' => array(array(
\'taxonomy\' => $taxonomy,
\'terms\' => $term->term_id
))
));
foreach ($posts as $post) {
$posts_data[$term->name][$post->ID] = array ($post->post_title);
}
}
?>
<div class="accordion-container">
<ul class="outer-border">
<?php foreach ($posts_data as $category => $posts) { ?>
<li class="control-section accordion-section">
<h3 class="accordion-section-title hndle" tabindex="0">
<?php echo $category; ?>
</h3>
<?php foreach ($posts as $post) { ?>
<div class="accordion-section-content" style="display: none;">
<label class="menu-item-title ">
<div><input type="checkbox" class="menu-item-checkbox" value="<?php echo $field_type->_id=$post->ID; ?>">
<span><?php echo $post[0]; ?></span>
<input type="text">
</div>
</label>
</div>
<?php } ?>
</li>
<?php } ?>
</ul>
</div>
<?php
}
用法:
add_action( \'cmb2_admin_init\', function () {
$prefix = \'recipes_\';
$cmb_recipes = new_cmb2_box( array(
\'id\' => $prefix . \'metabox\',
\'title\' => \'Posts multicheck by category\',
\'object_types\' => array( \'recipes\', ), // post type
) );
$cmb_recipes->add_field( array(
\'name\' => \'\',
\'id\' => $prefix . \'ingredients\',
\'type\' => \'post_multicheck_by_category\',
\'context\' => \'side\',
\'query_args\' => array (
\'post_type\' => \'ingredients\',
\'taxonomy\' => \'ingredients-category\',
),
) );
} );