我创建了两种自定义帖子类型,buildings
和availabilities
, 并添加了一个关于可用性的查询,以选择它所属的建筑,但我似乎无法保存它。
add_action(\'admin_init\', \'p2p2_add_building_metabox\');
function p2p2_add_building_metabox(){
add_meta_box(
\'building_availability\',
__(\'Building\', \'bandpress\'),
\'p2p2_building_availability_metabox\',
\'availabilities\',
\'side\',
\'default\',
array( \'id\' => \'p2p2_building\')
);}
function p2p2_building_availability_metabox($post, $args) {
wp_nonce_field( plugin_basename( __FILE__ ), \'p2p2_building_nonce\' );
$building_id = get_post_meta($post->ID, \'p2p2_building\', true);
echo "<p>Select The Building of This Availability</p>";
echo "<select id=\'p2p2_building\' name=\'p2p2_building\'>";
// Query the buildings here
$query = new WP_Query( \'post_type=building\' );
while ( $query->have_posts() ) {
$query->the_post();
$id = get_the_ID();
$selected = "";
if ($id == $author_id) {
$selected = \' selected="selected"\';
}
echo \'<option\' . $selected . \' value=\' . $id . \'>\' . get_the_title() . \'</option>\';
}
echo "</select>";
}
add_action(\'save_post\', \'p2p2_save_building_metabox\', 1, 2);
function p2p2_save_building_metabox($post_id, $post){
// Don\'t wanna save this now, right?
if ( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE )
return;
if ( !isset( $_POST[\'p2p2_building_nonce\'] ) )
return;
if ( !wp_verify_nonce( $_POST[\'p2p2_building_nonce\'], plugin_basename( __FILE__ ) ) )
return;
// We do want to save? Ok!
$key = \'p2p2_building\';
$value = $_POST["p2p2_building"];
if ( get_post_meta( $post->ID, $key, FALSE ) ) { // If the custom field already has a value
update_post_meta( $post->ID, $key, $value );
} else { // If the custom field doesn\'t have a value
add_post_meta( $post->ID, $key, $value );
}
if ( !$value )
delete_post_meta( $post->ID, $key ); // Delete if blank
}
SO网友:LWS-Mo
似乎您的代码中有一个错误。。。
if($id == $author_id){
$selected = \' selected="selected"\';
}
应该是这样的
$building_id
而不是
$author_id
.
我测试了其余代码,保存效果很好。
如果您打印/回显了此行的值。。。
$building_id = get_post_meta($post->ID, \'p2p2_building\', true);
喜欢
print_r($building_id);
, 您会看到,正确的帖子ID已经保存。因此,只有您的select元素无法设置;选定的(&Q);属性正确。
P、 可能您还想在选择字段中添加一个空的默认选项。由于有时用户不会填写此字段,因此第一个选项post ID总是会被保存。
类似于。。。
echo "<select id=\'p2p2_building\' name=\'p2p2_building\'>";
// empty default option:
echo "<option value="">Select building...</option>";