我试图创建一个带有复选框的自定义元框,该复选框是从自定义帖子类型的循环生成的。我发现this example 这里是关于WP开发的,但我不明白为什么这些盒子不能保存。
我的代码如下所示:
function anwaelte_display_meta_box( $post ) {
global $loop_anwaelte;
$loop_anwaelte = array();
wp_nonce_field( plugin_basename( __FILE__ ), \'anwaelte-nonce-field\' );
$args = array(
\'post_type\' => \'anwaelte\',
\'orderby\' => \'title\',
\'order\' => \'ASC\'
);
$query_anwaelte = new WP_Query( $args );
while ( $query_anwaelte->have_posts() ) : $query_anwaelte->the_post();
$id_anwalt = get_the_ID();
$anwalt = get_post( $id_brand, ARRAY_A );
$slug_anwalt = $anwalt[\'post_name\'];
$titolo_anwalt = $anwalt[\'post_title\'];
$loop_anwaelte[] = $slug_anwalt;
?>
<p>
<input type="checkbox" id="<?php echo $slug_anwalt; ?>" name="<?php
echo $slug_anwalt; ?>" value="yes" <?php
checked( get_post_meta( $post->ID, $slug_anwalt, true ), \'yes\' );
?>><label for="<?php echo $slug_anwalt; ?>"><?php
echo $titolo_anwalt; ?></label>
</p>
<?php
endwhile;
}
function anwaelte_add_meta_box() {
add_meta_box(
\'anwaelte-meta-box\',
\'Autor festlegen\',
\'anwaelte_display_meta_box\',
\'insights\',
\'side\',
\'low\'
);
}
add_action( \'add_meta_boxes\', \'anwaelte_add_meta_box\' );
function anwaelte_user_can_save( $post_id, $nonce ) {
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ $nonce ] ) && wp_verify_nonce( $_POST[ $nonce ],
plugin_basename( __FILE__ ) ) );
return ! ( $is_autosave || $is_revision ) && $is_valid_nonce;
}
function anwaelte_save_meta_box( $post_id ) {
global $loop_anwaelte;
foreach ( $loop_anwaelte as $anwalt ) {
if ( anwaelte_user_can_save( $post_id, $anwalt ) ) {
if ( isset( $_POST[ $anwalt ] ) ) {
update_post_meta( $post_id, $anwalt, $_POST[ $anwalt ] );
} else {
delete_post_meta( $post_id, $anwalt );
}
}
}
}
add_action( \'save_post\', \'anwaelte_save_meta_box\' );
我的第二个问题是,我不知道如何在insight自定义帖子中加载和显示选中的帖子(anwaelte)。我必须再次使用循环吗?