【发布时间】:2014-10-20 18:09:06
【问题描述】:
我创建了一个自定义元框,您可以在其中从一些单选按钮中选择一个值并将其保存到 wordpress 数据库中的 post_meta 表中。使用以下代码保存值:
function save_value_of_my_custom_metabox ($post_id, $post){
$post_id = get_the_ID();
$new_meta_value = ( isset( $_POST['the_name_of_the_radio_buttons'] ) ? sanitize_html_class( $_POST['the_name_of_the_radio_buttons'] ) : '' );
$meta_key = 'my_key';
update_post_meta( $post_id, $meta_key, $new_meta_value );
}
但如果要再次编辑帖子,我希望选中设置当前值的单选按钮。最好的方法是什么?这是显示元框的函数:
function my_custom_meta_box( $object, $box ) {
$post_id=get_the_ID();
$key='my_key';
$the_value_that_should_be_set_to_checked=get_post_meta( $post_id, $key);
//$the_value_that_should_be_set_to_checked[0] returns the value as string
?>
<label for="my_custom_metabox"><?php _e( "Choose value:", 'choose_value' ); ?></label>
<br />
<input type="radio" name="the_name_of_the_radio_buttons" value="value1">Value1<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value2">Value2<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value3">Value3<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value4">Value4<br>
<?php
}
我可以在每一行写if(isset($the_value_that_should_be_set_to_checked[0])=="value of that line") echo "checked='checked'"; 之类的东西,但这对我来说似乎不是很优雅。在 wordpress 中使用 javascript 也非常复杂,因为我必须使用钩子,将脚本排入队列,并且只是为了用一行 javascript 更改选中的属性,这是不值得的。最好的做法是什么?
【问题讨论】:
-
提供你用过的动作钩子。
-
add_action('load-post.php', 'my_custom_meta_box_setup'); add_action('load-post-new.php', 'my_custom_meta_box_setup');并在设置函数中: add_action( 'add_meta_boxes', 'my_custom__meta_box' );和 add_action( 'save_post', 'save_value_of_my_custom_metabox', 10, 2 );
标签: wordpress radio-button checked meta-boxes