实际上,问题是我给了select选项一个“parent\\u id”的名称,对于某些人来说,它是自动用作post parent的,但一旦我将其更改为其他名称,它就会起作用。
工作代码:
<?php
function hfx_register_meta_boxes() {
add_meta_box( \'select_hfx_workshop\', __( \'Workshop for\', HFX_DOMAIN ), \'hfx_select_workshop_parent_meta_box\', \'forum\', \'side\',\'core\');
}
add_action( \'add_meta_boxes_forum\', \'hfx_register_meta_boxes\' );
function hfx_select_workshop_parent_meta_box(){
global $post;
$selected = \'\';
wp_nonce_field( \'select_workshophfx_box_action\', \'select_workshophfx_box\' );
if(get_post_meta( $post->ID, \'workshop_id\', true )){
$selected = get_post_meta( $post->ID, \'workshop_id\', true );
}
if(post_type_exists( \'product\' )){
$workshopsfx = get_posts(
array(
\'post_type\' => \'product\',
\'orderby\' => \'title\',
\'order\' => \'ASC\',
\'numberposts\' => -1
)
);
if ( !empty( $workshopsfx ) ) {
echo \'<select name="workshop_id" class="widefat">\';
echo \'<option value="">\'.esc_html__(\'Choose a workshop\', HFX_DoMAIN).\'</option>\';
foreach ( $workshopsfx as $workshop ) {
printf( \'<option value="%s"%s>%s</option>\', esc_attr( $workshop->ID ), selected( $workshop->ID, $selected, false ), esc_html( $workshop->post_title ) );
}
echo \'</select>\';
}
}
}
function hfx_save_meta_box( $post_id ) {
if ( !isset( $_POST[\'select_workshophfx_box\'] ) || !wp_verify_nonce( $_POST[\'select_workshophfx_box\'], \'select_workshophfx_box_action\' ) ){
return;
}
if ( ! current_user_can( \'edit_post\', $post_id ) ){
return;
}
if ( $parent_id = wp_is_post_revision( $post_id ) ) {
$post_id = $parent_id;
}
$fields = [
\'workshop_id\',
];
foreach ( $fields as $field ) {
if ( array_key_exists( $field, $_POST ) ) {
update_post_meta( $post_id, $field, sanitize_text_field( $_POST[$field] ) );
}
}
}